Merge pull request #7 from alibaba/master

pull latest code
This commit is contained in:
pader 2019-03-01 13:59:24 +08:00 committed by GitHub
commit 89c1ae5b10
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
161 changed files with 2788 additions and 8200 deletions

28
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@ -0,0 +1,28 @@
<!-- Here is for bug reports and feature requests ONLY!
If you're looking for help, please check our mail list、WeChat group and the Gitter room.
Please try to use English to describe your issue, or at least provide a snippet of English translation.
我们鼓励使用英文,如果不能直接使用,可以使用翻译软件,您仍旧可以保留中文原文。
-->
## Issue Description
Type: *bug report* or *feature request*
### Describe what happened (or what feature you want)
### Describe what you expected to happen
### How to reproduce it (as minimally and precisely as possible)
1.
2.
3.
### Tell us your environment
### Anything else we need to know?

View File

@ -1,43 +0,0 @@
---
name: Bug report
about: Describe this issue template's purpose here.
---
# Reporting bugs
If any part of the Nacos project has bugs or documentation mistakes, please let us know by [opening an issue](https://github.com/alibaba/nacos/issues/new). We treat bugs and mistakes very seriously and believe no issue is too small, anyOne is implement. Before creating a bug report, please check that an issue reporting the same problem does not already exist.
To make the bug report accurate and easy to understand, please try to create bug reports that are:
- Specific. Include as much details as possible: which version, what environment, what configuration, etc. If the bug is related to running the Nacos server, please attach the Nacos log (the starting log with Nacos configuration is especially important).
- Reproducible. Include the steps to reproduce the problem. We understand some issues might be hard to reproduce, please includes the steps that might lead to the problem. If possible, please attach the affected Nacos data dir and stack strace to the bug report.
- Unique. Do not duplicate existing bug report.
It may be worthwhile to read [Elika Etemads article on filing good bug reports](http://fantasai.inkedblade.net/style/talks/filing-good-bugs/) before creating a bug report.
We might ask for further information to locate a bug. A duplicated bug report will be closed.
# 报告错误
如果Nacos项目的任何部分存在问题或文档问题请通过[opening an issue](https://github.com/alibaba/nacos/issues/new)告诉我们。我们非常认真地对待错误和错误在产品面前没有不重要的问题。不过在创建错误报告之前请检查是否存在报告相同问题的issues。
为了使错误报告准确且易于理解,请尝试创建以下错误报告:
- 具体到细节。包括尽可能多的细节哪个版本什么环境什么配置等。如果错误与运行Nacos服务器有关请附加Nacos日志具有Nacos配置的起始日志尤为重要
- 可复现。包括重现问题的步骤。我们理解某些问题可能难以重现请包括可能导致问题的步骤。如果可能请将受影响的Nacos数据目录和堆栈strace附加到错误报告中。
- 不重复。不要复制现有的错误报告。
在创建错误报告之前,最好阅读下[Elika Etemad关于提交好错误报告的文章](http://fantasai.inkedblade.net/style/talks/filing-good-bugs/),相信 会给你启发。
我们可能会要求您提供更多信息以查找错误。将关闭重复的错误报告。
[nacos-issue](https://github.com/alibaba/nacos/issues/new)
[filing-good-bugs](http://fantasai.inkedblade.net/style/talks/filing-good-bugs/)

View File

@ -1,17 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -1,3 +1,52 @@
## 0.9.0(Feb 28, 2019)
* [#840] Nacos server adds startup mode to distinguish between config and naming.
* [#762] Register instance returns failed when the health check mode is 'server' in standalone mode.
* [#473] Nacos Cluster Mode kubernate Startup nacos.log error Log.
* [#240] Log strong dependence problem.
* [#824] getServicesOfServer throws exception if service list is empty.
* [#802] Nacos server multi-boot mode support.
* [#800] Nacos's client-to-server addressing mode document introduction.
* [#768] The interval at which the heartbeat is sent in BeatReactor is not controlled by the server return value.
* [#759] why instance can't auto-delete.
* [#756] Format of instance and service should be validated.
* [#720] Memory leak in PushService.
* [#653] IoUtils under nacos-common-0.2.1-RC1.jar lacks "" judgment on encoding.
* [#588] Client compatible to jdk1.6.
## 0.8.0(Jan 22, 2019) PRE-GA
* [#162] Support open metrics and prometheus
* [#268] Health check is performed in the Nacos startup script
* [#320] Nacos supports multiple configuration files, configuration template abstraction and inheritance
* [#333] Use nacos in k8s to get hostname exception
* [#335] update nacos.io docker img priority/low
* [#339] Project language problem identified in github
* [#381] DiscussHow to support Login
* [#397] Some questions for Nacos
* [#402] When the configuration is added or edited, the edit box will not come out
* [#462] Nacos monitor discuss (0.8 version)
* [#496] Warning log printing when quering a nonexistent service
* [#497] Make subscription of service triggered by getInstance method optional
* [#498] Support namespace for service discovery
* [#499] When the configuration is newly created (if data-id and group already exist), the original configuration will be overwritten
* [#512] nacos-logs start.out always print 8848 (but port can be changed)
* [#514] Nacos 0.7 not support namespace
* [#523] Add a switch to control server detection and client reporting heartbeat switching
* [#526] Possible data loss in server side health check mode
* [#527] Many repeat client beat tasks can be generated
* [#558] Enable access log recording by default
* [#560] Nacos server startup issues
* [#579] New API support - “update health in none health check mode through api”
* [#587] Client sends request concurrently
* [#592] Service restful interface put/post is reversed
* [#599] getSubscribeServices method gets services that were deregistered
* [#603] Format log of naming module
* [#609] Always print a NPE log at start
* [#663] Nacos update instance info NPE
* [#668] 0.8.0-SNAPSHOT naming heartbeat not compatible with lower version client
* [#672] Startup.cmd bug
## 0.7.0(Dec, 2018)
* [ #461 ] Registration failed when instance port is set to 0

View File

@ -40,9 +40,9 @@ It is super easy to get started with your first project.
You can download the package from the [latest stable release](https://github.com/alibaba/nacos/releases).
Take release nacos-server-0.7.0.zip for example.
Take release nacos-server-0.9.0.zip for example.
```
unzip nacos-server-0.7.0.zip
unzip nacos-server-0.9.0.zip
cd nacos/bin
```
@ -100,3 +100,55 @@ Contributors are welcomed to join Nacos project. Please check [CONTRIBUTING](./C
* Join us from wechat. Welcome words: Nacos.
![cwex](http://acm-public.oss-cn-hangzhou.aliyuncs.com/xuc.png)
## Who is using
These are only part of the companies using Nacos, for reference only. If you are using Nacos, please [add your company here](https://github.com/alibaba/nacos/issues/273) to tell us your scenario to make Nacos better.
![Alibaba Group](https://docs.alibabagroup.com/assets2/images/en/global/logo_header.png)
![虎牙直播](https://a.msstatic.com/huya/main/img/logo.png)
![ICBC](http://v.icbc.com.cn/userfiles/Resources/ICBC/shouye/images/2017/logo.png)
![爱奇艺](http://www.iqiyipic.com/common/fix/site-v4/sprite-headLogo-index.png)
![平安科技](https://img.alicdn.com/tfs/TB1pwi9EwHqK1RjSZJnXXbNLpXa-479-59.png)
![华夏信财](https://img.alicdn.com/tfs/TB1MZWSEzDpK1RjSZFrXXa78VXa-269-69.png)
![优客工场](https://www.urwork.cn/public/images/ui/logo.png)
![贝壳找房](https://img.alicdn.com/tfs/TB1ebu.EAvoK1RjSZFwXXciCFXa-224-80.png)
![瑞安农村商业银行](https://img.alicdn.com/tfs/TB1lxu7EBLoK1RjSZFuXXXn0XXa-409-74.png)
![司法大数据](https://img.alicdn.com/tfs/TB1L16eEzTpK1RjSZKPXXa3UpXa-302-50.png)
![搜易贷](https://www.souyidai.com/www-style/images/logo.gif)
![美菜](https://www.meicai.cn/assets/images/new-img/logo.png)
![松格科技](http://songe.so/images/logo.gif)
![平行云](https://img.alicdn.com/tfs/TB1OigyDyLaK1RjSZFxXXamPFXa-168-70.png)
![甘肃紫光](https://img.alicdn.com/tfs/TB1gJ4vIhTpK1RjSZR0XXbEwXXa-462-60.jpg)
![海云天](http://www.seaskylight.com/cn/uploadfiles/image/logo.png)
![集萃智能](http://www.iimt.org.cn/pic/logosy.png)
![Acmedcare+](https://img.alicdn.com/tfs/TB1DZWSEzDpK1RjSZFrXXa78VXa-240-62.png)
![吾享](https://w.wuuxiang.com/theme/images/common/logo1.png)
![北京天合互联信息有限公司](http://14605854.s21i.faiusr.com/4/ABUIABAEGAAg4OvkzwUo8b-qlwUwxQ449gM!300x300.png)
![上海密尔克卫化工](http://www.mwclg.com/static-resource/front/images/home/img_logo_nav.png)
![大连新唯](https://www.synwe.com/logo-full.png)
![立思辰](https://user-images.githubusercontent.com/10215557/51593180-7563af00-1f2c-11e9-95b1-ec2c645d6a0b.png)
![拓深科技](http://www.tpson.cn/images/new/icon/LOGO_1.png)
![东家](https://img.alicdn.com/tfs/TB1zWW2EpYqK1RjSZLeXXbXppXa-262-81.png)
![上海克垚](http://www.sh-guiyao.com/images/logo.jpg)
![郑州山水](http://www.zzssxx.com/style/images/logo.png)
![联采科技](http://www.lckjep.com:80//theme/img/logoTop.png)
![南京28研究所](https://img.alicdn.com/tfs/TB1G216EsbpK1RjSZFyXXX_qFXa-325-53.jpg)
![长亮科技](http://www.sunline.cn/Uploads/image/20170724/59759a405c3b2.png)
![深圳易停车库](http://www.ytparking.com/yiting/images/logo.png)
![凤凰网-汽车](https://p1.ifengimg.com/auto/image/2017/0922/auto_logo.png)
![武汉日创科技](http://www.dragonwake.cn/static/css/default/images/logo.png)
![易管智能](http://ebmsw.mro1598.com/UpLoadFile/MainCompany/20170308-1501-495c-a62f-fc03424f86f1/20170405/20170405-1056-4fe5-90e8-c055f8a1bb23.png)
![云帐房](http://www.yunzhangfang.com/yzf-pc/img/logo.png)
![知氏教育](https://www.chyeth.com/622e88980a5d091eaa6449f82d48ca43.png)
![中化信息](http://www.sinochem.com/Portals/0/xinlogo.png)
![海格管家](https://img.alicdn.com/tfs/TB1FNq4EwHqK1RjSZFgXXa7JXXa-232-232.jpg)
![Nepxion](https://avatars0.githubusercontent.com/u/16344119?s=200&v=4)
![东莞最佳拍档](https://img.alicdn.com/tfs/TB11ugsDzTpK1RjSZKPXXa3UpXa-300-300.png)
![chigua](https://img.alicdn.com/tfs/TB1aUe5EpzqK1RjSZSgXXcpAVXa-248-124.png)
![宅无限](https://img.alicdn.com/tfs/TB1H9O5EAvoK1RjSZFNXXcxMVXa-221-221.jpg)
![天阙](https://img.alicdn.com/tfs/TB1rNq4EwHqK1RjSZFgXXa7JXXa-200-200.jpg)
![联合永道](https://img.alicdn.com/tfs/TB1CRAxDxYaK1RjSZFnXXa80pXa-190-190.jpg)
![明源云](https://img.alicdn.com/tfs/TB1.q14ErrpK1RjSZTEXXcWAVXa-219-219.jpg)

View File

@ -16,7 +16,7 @@
<parent>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId>
<version>0.8.0</version>
<version>0.9.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -32,8 +32,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>

View File

@ -16,7 +16,7 @@
<parent>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId>
<version>0.8.0</version>
<version>0.9.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -43,7 +43,6 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
<optional>true</optional>
</dependency>
@ -108,9 +107,22 @@
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-core</artifactId>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient</artifactId>
<version>0.5.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -30,12 +30,11 @@ import com.alibaba.nacos.client.config.impl.ClientWorker;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult;
import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor;
import com.alibaba.nacos.client.config.utils.ContentUtils;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.config.utils.ParamUtils;
import com.alibaba.nacos.client.config.utils.TenantUtil;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.StringUtils;
import org.slf4j.Logger;
import java.io.IOException;
import java.net.HttpURLConnection;
@ -52,8 +51,9 @@ import java.util.Properties;
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
public class NacosConfigService implements ConfigService {
final static public Logger log = LogUtils.logger(NacosConfigService.class);
public final long POST_TIMEOUT = 3000L;
private static final Logger LOGGER = LogUtils.logger(NacosConfigService.class);
private final long POST_TIMEOUT = 3000L;
/**
* http agent
*/
@ -123,8 +123,8 @@ public class NacosConfigService implements ConfigService {
// 优先使用本地配置
String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant);
if (content != null) {
log.warn(agent.getName(), "[get-config] get failover ok, dataId={}, group={}, tenant={}, config={}", dataId,
group, tenant, ContentUtils.truncateContent(content));
LOGGER.warn("[{}] [get-config] get failover ok, dataId={}, group={}, tenant={}, config={}", agent.getName(),
dataId, group, tenant, ContentUtils.truncateContent(content));
cr.setContent(content);
configFilterChainManager.doFilter(null, cr);
content = cr.getContent();
@ -143,14 +143,12 @@ public class NacosConfigService implements ConfigService {
if (NacosException.NO_RIGHT == ioe.getErrCode()) {
throw ioe;
}
log.warn("NACOS-0003",
LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0003", "环境问题", "get from server error"));
log.warn(agent.getName(), "[get-config] get from server error, dataId={}, group={}, tenant={}, msg={}",
dataId, group, tenant, ioe.toString());
LOGGER.warn("[{}] [get-config] get from server error, dataId={}, group={}, tenant={}, msg={}",
agent.getName(), dataId, group, tenant, ioe.toString());
}
log.warn(agent.getName(), "[get-config] get snapshot ok, dataId={}, group={}, tenant={}, config={}", dataId,
group, tenant, ContentUtils.truncateContent(content));
LOGGER.warn("[{}] [get-config] get snapshot ok, dataId={}, group={}, tenant={}, config={}", agent.getName(),
dataId, group, tenant, ContentUtils.truncateContent(content));
content = LocalConfigInfoProcessor.getSnapshot(agent.getName(), dataId, group, tenant);
cr.setContent(content);
configFilterChainManager.doFilter(null, cr);
@ -183,20 +181,20 @@ public class NacosConfigService implements ConfigService {
try {
result = agent.httpDelete(url, null, params, encode, POST_TIMEOUT);
} catch (IOException ioe) {
log.warn("[remove] error, " + dataId + ", " + group + ", " + tenant + ", msg: " + ioe.toString());
LOGGER.warn("[remove] error, " + dataId + ", " + group + ", " + tenant + ", msg: " + ioe.toString());
return false;
}
if (HttpURLConnection.HTTP_OK == result.code) {
log.info(agent.getName(), "[remove] ok, dataId={}, group={}, tenant={}", dataId, group, tenant);
LOGGER.info("[{}] [remove] ok, dataId={}, group={}, tenant={}", agent.getName(), dataId, group, tenant);
return true;
} else if (HttpURLConnection.HTTP_FORBIDDEN == result.code) {
log.warn(agent.getName(), "[remove] error, dataId={}, group={}, tenant={}, code={}, msg={}", dataId, group,
tenant, result.code, result.content);
LOGGER.warn("[{}] [remove] error, dataId={}, group={}, tenant={}, code={}, msg={}", agent.getName(), dataId,
group, tenant, result.code, result.content);
throw new NacosException(result.code, result.content);
} else {
log.warn(agent.getName(), "[remove] error, dataId={}, group={}, tenant={}, code={}, msg={}", dataId, group,
tenant, result.code, result.content);
LOGGER.warn("[{}] [remove] error, dataId={}, group={}, tenant={}, code={}, msg={}", agent.getName(), dataId,
group, tenant, result.code, result.content);
return false;
}
}
@ -245,24 +243,22 @@ public class NacosConfigService implements ConfigService {
try {
result = agent.httpPost(url, headers, params, encode, POST_TIMEOUT);
} catch (IOException ioe) {
log.warn("NACOS-0006",
LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0006", "环境问题", "[publish-single] exception"));
log.warn(agent.getName(), "[publish-single] exception, dataId={}, group={}, msg={}", dataId, group,
ioe.toString());
LOGGER.warn("[{}] [publish-single] exception, dataId={}, group={}, msg={}", agent.getName(), dataId,
group, ioe.toString());
return false;
}
if (HttpURLConnection.HTTP_OK == result.code) {
log.info(agent.getName(), "[publish-single] ok, dataId={}, group={}, tenant={}, config={}", dataId, group,
tenant, ContentUtils.truncateContent(content));
LOGGER.info("[{}] [publish-single] ok, dataId={}, group={}, tenant={}, config={}", agent.getName(), dataId,
group, tenant, ContentUtils.truncateContent(content));
return true;
} else if (HttpURLConnection.HTTP_FORBIDDEN == result.code) {
log.warn(agent.getName(), "[publish-single] error, dataId={}, group={}, tenant={}, code={}, msg={}", dataId,
group, tenant, result.code, result.content);
LOGGER.warn("[{}] [publish-single] error, dataId={}, group={}, tenant={}, code={}, msg={}", agent.getName(),
dataId, group, tenant, result.code, result.content);
throw new NacosException(result.code, result.content);
} else {
log.warn(agent.getName(), "[publish-single] error, dataId={}, group={}, tenant={}, code={}, msg={}", dataId,
group, tenant, result.code, result.content);
LOGGER.warn("[{}] [publish-single] error, dataId={}, group={}, tenant={}, code={}, msg={}", agent.getName(),
dataId, group, tenant, result.code, result.content);
return false;
}

View File

@ -18,10 +18,10 @@ package com.alibaba.nacos.client.config.http;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import io.prometheus.client.Histogram;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* MetricsHttpAgent
@ -42,57 +42,49 @@ public class MetricsHttpAgent implements HttpAgent {
@Override
public HttpResult httpGet(String path, List<String> headers, List<String> paramValues, String encoding, long readTimeoutMs) throws IOException {
long start = System.currentTimeMillis();
long end = 0;
Histogram.Timer timer = MetricsMonitor.getConfigRequestMonitor("GET", path, "NA");
HttpResult result = null;
try {
result = httpAgent.httpGet(path, headers, paramValues, encoding, readTimeoutMs);
} catch (IOException e) {
end = System.currentTimeMillis();
MetricsMonitor.getConfigRequestMonitor("GET", path, "NA").record(end - start, TimeUnit.MILLISECONDS);
throw e;
} finally {
timer.observeDuration();
timer.close();
}
end = System.currentTimeMillis();
MetricsMonitor.getConfigRequestMonitor("GET", path, String.valueOf(result.code)).record(end - start, TimeUnit.MILLISECONDS);
return result;
}
@Override
public HttpResult httpPost(String path, List<String> headers, List<String> paramValues, String encoding, long readTimeoutMs) throws IOException {
long start = System.currentTimeMillis();
long end = 0;
Histogram.Timer timer = MetricsMonitor.getConfigRequestMonitor("POST", path, "NA");
HttpResult result = null;
try {
result = httpAgent.httpPost(path, headers, paramValues, encoding, readTimeoutMs);
} catch (IOException e) {
end = System.currentTimeMillis();
MetricsMonitor.getConfigRequestMonitor("POST", path, "NA").record(end - start, TimeUnit.MILLISECONDS);
throw e;
} finally {
timer.observeDuration();
timer.close();
}
end = System.currentTimeMillis();
MetricsMonitor.getConfigRequestMonitor("POST", path, String.valueOf(result.code)).record(end - start, TimeUnit.MILLISECONDS);
return result;
}
@Override
public HttpResult httpDelete(String path, List<String> headers, List<String> paramValues, String encoding, long readTimeoutMs) throws IOException {
long start = System.currentTimeMillis();
long end = 0;
Histogram.Timer timer = MetricsMonitor.getConfigRequestMonitor("DELETE", path, "NA");
HttpResult result = null;
try {
result = httpAgent.httpDelete(path, headers, paramValues, encoding, readTimeoutMs);
} catch (IOException e) {
end = System.currentTimeMillis();
MetricsMonitor.getConfigRequestMonitor("DELETE", path, "NA").record(end - start, TimeUnit.MILLISECONDS);
throw e;
}
end = System.currentTimeMillis();
MetricsMonitor.getConfigRequestMonitor("DELETE", path, String.valueOf(result.code)).record(end - start, TimeUnit.MILLISECONDS);
throw e;
} finally {
timer.observeDuration();
timer.close();
}
return result;
}
@ -117,3 +109,4 @@ public class MetricsHttpAgent implements HttpAgent {
return httpAgent.getEncode();
}
}

View File

@ -23,16 +23,14 @@ import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult;
import com.alibaba.nacos.client.config.impl.ServerListManager;
import com.alibaba.nacos.client.config.impl.SpasAdapter;
import com.alibaba.nacos.client.config.utils.IOUtils;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.identify.STSConfig;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import java.io.IOException;
import java.net.ConnectException;
@ -43,7 +41,6 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
* Server Agent
@ -52,7 +49,7 @@ import java.util.concurrent.TimeUnit;
*/
public class ServerHttpAgent implements HttpAgent {
final static public Logger log = LogUtils.logger(ServerHttpAgent.class);
private static final Logger LOGGER = LogUtils.logger(ServerHttpAgent.class);
/**
* @param path 相对于web应用根/开头
@ -82,28 +79,24 @@ public class ServerHttpAgent implements HttpAgent {
if (result.code == HttpURLConnection.HTTP_INTERNAL_ERROR
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}",
serverListMgr.getCurrentServerAddr(), result.code);
} else {
return result;
}
} catch (ConnectException ce) {
log.error("NACOS ConnectException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS ConnectException] currentServerAddr:{}", serverListMgr.getCurrentServerAddr());
serverListMgr.refreshCurrentServerAddr();
} catch (SocketTimeoutException stoe) {
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS SocketTimeoutException] currentServerAddr:{}", serverListMgr.getCurrentServerAddr());
serverListMgr.refreshCurrentServerAddr();
} catch (IOException ioe) {
log.error("NACOS IOException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS IOException] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ioe);
throw ioe;
}
} while (System.currentTimeMillis() <= endTime);
log.error("NACOS-0002",
LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0002", "环境问题", "no available server"));
LOGGER.error("no available server");
throw new ConnectException("no available server");
}
@ -124,29 +117,26 @@ public class ServerHttpAgent implements HttpAgent {
if (result.code == HttpURLConnection.HTTP_INTERNAL_ERROR
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}",
serverListMgr.getCurrentServerAddr(), result.code);
} else {
return result;
}
} catch (ConnectException ce) {
log.error("NACOS ConnectException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS ConnectException] currentServerAddr: {}", serverListMgr.getCurrentServerAddr());
serverListMgr.refreshCurrentServerAddr();
} catch (SocketTimeoutException stoe) {
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS SocketTimeoutException]", "currentServerAddr: {}",
serverListMgr.getCurrentServerAddr());
serverListMgr.refreshCurrentServerAddr();
} catch (IOException ioe) {
log.error("NACOS IOException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS IOException] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ioe);
throw ioe;
}
} while (System.currentTimeMillis() <= endTime);
log.error("NACOS-0002",
LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0002", "环境问题", "no available server"));
LOGGER.error("no available server");
throw new ConnectException("no available server");
}
@ -167,29 +157,25 @@ public class ServerHttpAgent implements HttpAgent {
if (result.code == HttpURLConnection.HTTP_INTERNAL_ERROR
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}",
serverListMgr.getCurrentServerAddr(), result.code);
} else {
return result;
}
} catch (ConnectException ce) {
log.error("NACOS ConnectException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS ConnectException] currentServerAddr:{}", serverListMgr.getCurrentServerAddr());
serverListMgr.refreshCurrentServerAddr();
} catch (SocketTimeoutException stoe) {
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS SocketTimeoutException] currentServerAddr:{}", serverListMgr.getCurrentServerAddr());
serverListMgr.refreshCurrentServerAddr();
} catch (IOException ioe) {
log.error("NACOS IOException", "currentServerAddr:{}",
new Object[] {serverListMgr.getCurrentServerAddr()});
LOGGER.error("[NACOS IOException] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ioe);
throw ioe;
}
} while (System.currentTimeMillis() <= endTime);
log.error("NACOS-0002",
LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0002", "环境问题", "no available server"));
LOGGER.error("no available server");
throw new ConnectException("no available server");
}
@ -290,7 +276,7 @@ public class ServerHttpAgent implements HttpAgent {
STSCredential stsCredentialTmp = (STSCredential)JSONUtils.deserializeObject(stsResponse,
new TypeReference<STSCredential>() {});
sTSCredential = stsCredentialTmp;
log.info("getSTSCredential", "code:{}, accessKeyId:{}, lastUpdated:{}, expiration:{}", sTSCredential.getCode(),
LOGGER.info("[getSTSCredential] code:{}, accessKeyId:{}, lastUpdated:{}, expiration:{}", sTSCredential.getCode(),
sTSCredential.getAccessKeyId(), sTSCredential.getLastUpdated(), sTSCredential.getExpiration());
return sTSCredential;
}
@ -317,7 +303,7 @@ public class ServerHttpAgent implements HttpAgent {
response = IOUtils.toString(conn.getErrorStream(), Constants.ENCODE);
}
} catch (IOException e) {
log.error("500", "can not get security credentials", e);
LOGGER.error("can not get security credentials", e);
throw e;
} finally {
if (null != conn) {
@ -327,8 +313,8 @@ public class ServerHttpAgent implements HttpAgent {
if (HttpURLConnection.HTTP_OK == respCode) {
return response;
}
log.error(respCode + "", "can not get security credentials, securityCredentialsUrl:{}, response:{}",
new Object[] {securityCredentialsUrl, response});
LOGGER.error("can not get security credentials, securityCredentialsUrl: {}, responseCode: {}, response: {}",
securityCredentialsUrl, respCode, response);
throw new IOException(
"can not get security credentials, responseCode: " + respCode + ", response: " + response);
}

View File

@ -21,10 +21,10 @@ import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.filter.impl.ConfigFilterChainManager;
import com.alibaba.nacos.client.config.filter.impl.ConfigResponse;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.config.utils.MD5;
import com.alibaba.nacos.client.config.utils.TenantUtil;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.utils.LogUtils;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
@ -37,7 +37,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
*/
public class CacheData {
final static public Logger log = LogUtils.logger(CacheData.class);
private static final Logger LOGGER = LogUtils.logger(CacheData.class);
public boolean isInitializing() {
return isInitializing;
@ -75,7 +75,7 @@ public class CacheData {
}
ManagerListenerWrap wrap = new ManagerListenerWrap(listener);
if (listeners.addIfAbsent(wrap)) {
log.info(name, "[add-listener] ok, tenant={}, dataId={}, group={}, cnt={}", tenant, dataId, group,
LOGGER.info("[{}] [add-listener] ok, tenant={}, dataId={}, group={}, cnt={}", name, tenant, dataId, group,
listeners.size());
}
}
@ -86,7 +86,7 @@ public class CacheData {
}
ManagerListenerWrap wrap = new ManagerListenerWrap(listener);
if (listeners.remove(wrap)) {
log.info(name, "[remove-listener] ok, dataId={}, group={}, cnt={}", dataId, group, listeners.size());
LOGGER.info("[{}] [remove-listener] ok, dataId={}, group={}, cnt={}", name, dataId, group, listeners.size());
}
}
@ -174,7 +174,7 @@ public class CacheData {
if (listener instanceof AbstractSharedListener) {
AbstractSharedListener adapter = (AbstractSharedListener)listener;
adapter.fillContext(dataId, group);
log.info(name, "[notify-context] dataId={}, group={}, md5={}", dataId, group, md5);
LOGGER.info("[{}] [notify-context] dataId={}, group={}, md5={}", name, dataId, group, md5);
}
// 执行回调之前先将线程classloader设置为具体webapp的classloader以免回调方法中调用spi接口是出现异常或错用多应用部署才会有该问题
Thread.currentThread().setContextClassLoader(appClassLoader);
@ -187,18 +187,14 @@ public class CacheData {
String contentTmp = cr.getContent();
listener.receiveConfigInfo(contentTmp);
listenerWrap.lastCallMd5 = md5;
log.info(
name,
"[notify-ok] dataId={}, group={}, md5={}, listener={} ",
dataId, group, md5, listener);
LOGGER.info("[{}] [notify-ok] dataId={}, group={}, md5={}, listener={} ", name, dataId, group, md5,
listener);
} catch (NacosException de) {
log.error(name, "NACOS-XXXX",
"[notify-error] dataId={}, group={}, md5={}, listener={} errCode={} errMsg={}", dataId,
group, md5, listener, de.getErrCode(), de.getErrMsg());
LOGGER.error("[{}] [notify-error] dataId={}, group={}, md5={}, listener={} errCode={} errMsg={}", name,
dataId, group, md5, listener, de.getErrCode(), de.getErrMsg());
} catch (Throwable t) {
log.error(name, "NACOS-XXXX",
"[notify-error] dataId={}, group={}, md5={}, listener={} tx={}", dataId, group, md5,
listener, t.getCause());
LOGGER.error("[{}] [notify-error] dataId={}, group={}, md5={}, listener={} tx={}", name, dataId, group,
md5, listener, t.getCause());
} finally {
Thread.currentThread().setContextClassLoader(myClassLoader);
}
@ -213,15 +209,12 @@ public class CacheData {
job.run();
}
} catch (Throwable t) {
log.error(
name,
"NACOS-XXXX",
"[notify-error] dataId={}, group={}, md5={}, listener={} throwable={}",
dataId, group, md5, listener, t.getCause());
LOGGER.error("[{}] [notify-error] dataId={}, group={}, md5={}, listener={} throwable={}", name, dataId, group,
md5, listener, t.getCause());
}
final long finishNotify = System.currentTimeMillis();
log.info(name, "[notify-listener] time cost={}ms in ClientWorker, dataId={}, group={}, md5={}, listener={} ",
(finishNotify - startNotify), dataId, group, md5, listener);
LOGGER.info("[{}] [notify-listener] time cost={}ms in ClientWorker, dataId={}, group={}, md5={}, listener={} ",
name, (finishNotify - startNotify), dataId, group, md5, listener);
}
static public String getMd5String(String config) {

View File

@ -23,22 +23,31 @@ import com.alibaba.nacos.client.config.filter.impl.ConfigFilterChainManager;
import com.alibaba.nacos.client.config.http.HttpAgent;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult;
import com.alibaba.nacos.client.config.utils.ContentUtils;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.config.utils.MD5;
import com.alibaba.nacos.client.config.utils.TenantUtil;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.slf4j.Logger;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static com.alibaba.nacos.api.common.Constants.LINE_SEPARATOR;
@ -51,7 +60,7 @@ import static com.alibaba.nacos.api.common.Constants.WORD_SEPARATOR;
*/
public class ClientWorker {
final static public Logger log = LogUtils.logger(ClientWorker.class);
private static final Logger LOGGER = LogUtils.logger(ClientWorker.class);
public void addListeners(String dataId, String group, List<? extends Listener> listeners) {
group = null2defaultGroup(group);
@ -101,7 +110,7 @@ public class ClientWorker {
copy.remove(groupKey);
cacheMap.set(copy);
}
log.info(agent.getName(), "[unsubscribe] {}", groupKey);
LOGGER.info("[{}] [unsubscribe] {}", agent.getName(), groupKey);
MetricsMonitor.getListenConfigCountMonitor().set(cacheMap.get().size());
}
@ -114,7 +123,7 @@ public class ClientWorker {
copy.remove(groupKey);
cacheMap.set(copy);
}
log.info(agent.getName(), "[unsubscribe] {}", groupKey);
LOGGER.info("[{}] [unsubscribe] {}", agent.getName(), groupKey);
MetricsMonitor.getListenConfigCountMonitor().set(cacheMap.get().size());
}
@ -147,7 +156,7 @@ public class ClientWorker {
cacheMap.set(copy);
}
log.info(agent.getName(), "[subscribe] {}", key);
LOGGER.info("[{}] [subscribe] {}", agent.getName(), key);
MetricsMonitor.getListenConfigCountMonitor().set(cacheMap.get().size());
@ -177,7 +186,7 @@ public class ClientWorker {
copy.put(key, cache);
cacheMap.set(copy);
}
log.info(agent.getName(), "[subscribe] {}", key);
LOGGER.info("[{}] [subscribe] {}", agent.getName(), key);
MetricsMonitor.getListenConfigCountMonitor().set(cacheMap.get().size());
@ -211,9 +220,10 @@ public class ClientWorker {
}
result = agent.httpGet(Constants.CONFIG_CONTROLLER_PATH, null, params, agent.getEncode(), readTimeout);
} catch (IOException e) {
log.error(agent.getName(), "NACOS-XXXX",
"[sub-server] get server config exception, dataId={}, group={}, tenant={}, msg={}", dataId, group,
tenant, e.toString());
String message = String.format(
"[%s] [sub-server] get server config exception, dataId=%s, group=%s, tenant=%s", agent.getName(),
dataId, group, tenant);
LOGGER.error(message, e);
throw new NacosException(NacosException.SERVER_ERROR, e.getMessage());
}
@ -225,20 +235,20 @@ public class ClientWorker {
LocalConfigInfoProcessor.saveSnapshot(agent.getName(), dataId, group, tenant, null);
return null;
case HttpURLConnection.HTTP_CONFLICT: {
log.error(agent.getName(), "NACOS-XXXX",
"[sub-server-error] get server config being modified concurrently, dataId={}, group={}, tenant={}",
dataId, group, tenant);
LOGGER.error(
"[{}] [sub-server-error] get server config being modified concurrently, dataId={}, group={}, "
+ "tenant={}", agent.getName(), dataId, group, tenant);
throw new NacosException(NacosException.CONFLICT,
"data being modified, dataId=" + dataId + ",group=" + group + ",tenant=" + tenant);
}
case HttpURLConnection.HTTP_FORBIDDEN: {
log.error(agent.getName(), "NACOS-XXXX", "[sub-server-error] no right, dataId={}, group={}, tenant={}",
dataId, group, tenant);
LOGGER.error("[{}] [sub-server-error] no right, dataId={}, group={}, tenant={}", agent.getName(), dataId,
group, tenant);
throw new NacosException(result.code, result.content);
}
default: {
log.error(agent.getName(), "NACOS-XXXX", "[sub-server-error] dataId={}, group={}, tenant={}, code={}",
dataId, group, tenant, result.code);
LOGGER.error("[{}] [sub-server-error] dataId={}, group={}, tenant={}, code={}", agent.getName(), dataId,
group, tenant, result.code);
throw new NacosException(result.code,
"http error, code=" + result.code + ",dataId=" + dataId + ",group=" + group + ",tenant=" + tenant);
}
@ -259,17 +269,16 @@ public class ClientWorker {
cacheData.setLocalConfigInfoVersion(path.lastModified());
cacheData.setContent(content);
log.warn(agent.getName(),
"[failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}",
dataId, group, tenant, md5, ContentUtils.truncateContent(content));
LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}",
agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content));
return;
}
// -> 没有不通知业务监听器从server拿到配置后通知
if (cacheData.isUseLocalConfigInfo() && !path.exists()) {
cacheData.setUseLocalConfigInfo(false);
log.warn(agent.getName(), "[failover-change] failover file deleted. dataId={}, group={}, tenant={}", dataId,
group, tenant);
LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(),
dataId, group, tenant);
return;
}
@ -281,9 +290,8 @@ public class ClientWorker {
cacheData.setUseLocalConfigInfo(true);
cacheData.setLocalConfigInfoVersion(path.lastModified());
cacheData.setContent(content);
log.warn(agent.getName(),
"[failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}",
dataId, group, tenant, md5, ContentUtils.truncateContent(content));
LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}",
agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content));
return;
}
}
@ -363,17 +371,11 @@ public class ClientWorker {
return parseUpdateDataIdResponse(result.content);
} else {
setHealthServer(false);
if (result.code == HttpURLConnection.HTTP_INTERNAL_ERROR) {
log.error("NACOS-0007", LoggerHelper.getErrorCodeStr("Nacos", "Nacos-0007", "环境问题",
"[check-update] get changed dataId error"));
}
log.error(agent.getName(), "NACOS-XXXX", "[check-update] get changed dataId error, code={}",
result.code);
LOGGER.error("[{}] [check-update] get changed dataId error, code: {}", agent.getName(), result.code);
}
} catch (IOException e) {
setHealthServer(false);
log.error(agent.getName(), "NACOS-XXXX", "[check-update] get changed dataId exception, msg={}",
e.toString());
LOGGER.error("[" + agent.getName() + "] [check-update] get changed dataId exception", e);
}
return Collections.emptyList();
}
@ -389,7 +391,7 @@ public class ClientWorker {
try {
response = URLDecoder.decode(response, "UTF-8");
} catch (Exception e) {
log.error(agent.getName(), "NACOS-XXXX", "[polling-resp] decode modifiedDataIdsString error", e);
LOGGER.error("[" + agent.getName() + "] [polling-resp] decode modifiedDataIdsString error", e);
}
List<String> updateList = new LinkedList<String>();
@ -401,15 +403,14 @@ public class ClientWorker {
String group = keyArr[1];
if (keyArr.length == 2) {
updateList.add(GroupKey.getKey(dataId, group));
log.info(agent.getName(), "[polling-resp] config changed. dataId={}, group={}", dataId, group);
LOGGER.info("[{}] [polling-resp] config changed. dataId={}, group={}", agent.getName(), dataId, group);
} else if (keyArr.length == 3) {
String tenant = keyArr[2];
updateList.add(GroupKey.getKeyTenant(dataId, group, tenant));
log.info(agent.getName(), "[polling-resp] config changed. dataId={}, group={}, tenant={}", dataId,
group, tenant);
LOGGER.info("[{}] [polling-resp] config changed. dataId={}, group={}, tenant={}", agent.getName(),
dataId, group, tenant);
} else {
log.error(agent.getName(), "NACOS-XXXX", "[polling-resp] invalid dataIdAndGroup error",
dataIdAndGroup);
LOGGER.error("[{}] [polling-resp] invalid dataIdAndGroup error {}", agent.getName(), dataIdAndGroup);
}
}
}
@ -446,7 +447,7 @@ public class ClientWorker {
try {
checkConfigInfo();
} catch (Throwable e) {
log.error(agent.getName(), "NACOS-XXXX", "[sub-check] rotate check error", e);
LOGGER.error("[" + agent.getName() + "] [sub-check] rotate check error", e);
}
}
}, 1L, 10L, TimeUnit.MILLISECONDS);
@ -472,7 +473,7 @@ public class ClientWorker {
cacheData.checkListenerMd5();
}
} catch (Exception e) {
log.error("NACOS-CLIENT", "get local config info error", e);
LOGGER.error("get local config info error", e);
}
}
}
@ -493,12 +494,14 @@ public class ClientWorker {
String content = getServerConfig(dataId, group, tenant, 3000L);
CacheData cache = cacheMap.get().get(GroupKey.getKeyTenant(dataId, group, tenant));
cache.setContent(content);
log.info(agent.getName(), "[data-received] dataId={}, group={}, tenant={}, md5={}, content={}",
dataId, group, tenant, cache.getMd5(), ContentUtils.truncateContent(content));
LOGGER.info("[{}] [data-received] dataId={}, group={}, tenant={}, md5={}, content={}",
agent.getName(), dataId, group, tenant, cache.getMd5(),
ContentUtils.truncateContent(content));
} catch (NacosException ioe) {
log.error(agent.getName(), "NACOS-XXXX",
"[get-update] get changed config exception. dataId={}, group={}, tenant={}, msg={}",
dataId, group, tenant, ioe.toString());
String message = String.format(
"[%s] [get-update] get changed config exception. dataId=%s, group=%s, tenant=%s",
agent.getName(), dataId, group, tenant);
LOGGER.error(message, ioe);
}
}
for (CacheData cacheData : cacheDatas) {
@ -510,7 +513,7 @@ public class ClientWorker {
}
inInitializingCacheList.clear();
} catch (Throwable e) {
log.error("500", "longPolling error", e);
LOGGER.error("longPolling error", e);
} finally {
executorService.execute(this);
}

View File

@ -15,15 +15,15 @@
*/
package com.alibaba.nacos.client.config.impl;
import com.alibaba.nacos.client.utils.LogUtils;
import org.slf4j.Logger;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.logger.Logger;
/**
* Event subscription and publishing tools.
*
@ -31,7 +31,7 @@ import com.alibaba.nacos.client.logger.Logger;
*/
public class EventDispatcher {
final static public Logger log = LogUtils.logger(EventDispatcher.class);
private static final Logger LOGGER = LogUtils.logger(EventDispatcher.class);
/**
* 添加事件监听器
@ -58,7 +58,7 @@ public class EventDispatcher {
fireEvent(implyEvent);
}
} catch (Exception e) {
log.warn("", e.toString(), e);
LOGGER.warn(e.toString(), e);
}
}
@ -66,7 +66,7 @@ public class EventDispatcher {
try {
listener.onEvent(abstractEvent);
} catch (Exception e) {
log.warn(e.toString(), e);
LOGGER.warn(e.toString(), e);
}
}
}

View File

@ -101,6 +101,7 @@ public class HttpSimpleClient {
static public HttpResult httpPost(String url, List<String> headers, List<String> paramValues,
String encoding, long readTimeoutMs, boolean isSSL) throws IOException {
String encodedContent = encodingParams(paramValues, encoding);
encodedContent = (null == encodedContent) ? "" : encodedContent;
if (Limiter.isLimit(MD5.getInstance().getMD5String(
new StringBuilder(url).append(encodedContent).toString()))) {
return new HttpResult(NacosException.CLIENT_OVER_THRESHOLD,

View File

@ -15,15 +15,15 @@
*/
package com.alibaba.nacos.client.config.impl;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.utils.LogUtils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* Limiter
@ -32,7 +32,8 @@ import com.google.common.util.concurrent.RateLimiter;
*/
public class Limiter {
static final public Logger log = LogUtils.logger(Limiter.class);
private static final Logger LOGGER = LogUtils.logger(Limiter.class);
private static int CAPACITY_SIZE = 1000;
private static int LIMIT_TIME = 1000;
private static Cache<String, RateLimiter> cache = CacheBuilder.newBuilder()
@ -49,9 +50,9 @@ public class Limiter {
String limitTimeStr = System
.getProperty("limitTime", String.valueOf(limit));
limit = Double.parseDouble(limitTimeStr);
log.info("limitTime:{}", limit);
LOGGER.info("limitTime:{}", limit);
} catch (Exception e) {
log.error("Nacos-xxx", "init limitTime fail", e);
LOGGER.error("init limitTime fail", e);
}
}
@ -65,10 +66,10 @@ public class Limiter {
}
});
} catch (ExecutionException e) {
log.error("Nacos-XXX", "create limit fail", e);
LOGGER.error("create limit fail", e);
}
if (rateLimiter != null && !rateLimiter.tryAcquire(LIMIT_TIME, TimeUnit.MILLISECONDS)) {
log.error("Nacos-XXX", "access_key_id:{} limited", accessKeyID);
LOGGER.error("access_key_id:{} limited", accessKeyID);
return true;
}
return false;

View File

@ -16,9 +16,13 @@
package com.alibaba.nacos.client.config.impl;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.config.utils.*;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.config.utils.ConcurrentDiskUtil;
import com.alibaba.nacos.client.config.utils.IOUtils;
import com.alibaba.nacos.client.config.utils.JVMUtil;
import com.alibaba.nacos.client.config.utils.SnapShotSwitch;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.StringUtils;
import org.slf4j.Logger;
import java.io.File;
import java.io.FileInputStream;
@ -32,7 +36,7 @@ import java.io.InputStream;
*/
public class LocalConfigInfoProcessor {
final static public Logger log = LogUtils.logger(LocalConfigInfoProcessor.class);
private static final Logger LOGGER = LogUtils.logger(LocalConfigInfoProcessor.class);
static public String getFailover(String serverName, String dataId, String group, String tenant) {
File localPath = getFailoverFile(serverName, dataId, group, tenant);
@ -43,7 +47,7 @@ public class LocalConfigInfoProcessor {
try {
return readFile(localPath);
} catch (IOException ioe) {
log.error(serverName, "NACOS-XXXX", "get failover error, " + localPath + ioe.toString());
LOGGER.error("[" + serverName + "] get failover error, " + localPath, ioe);
return null;
}
}
@ -63,7 +67,7 @@ public class LocalConfigInfoProcessor {
try {
return readFile(file);
} catch (IOException ioe) {
log.error(name, "NACOS-XXXX", "get snapshot error, " + file + ", " + ioe.toString());
LOGGER.error("[" + name + "]+get snapshot error, " + file, ioe);
return null;
}
}
@ -100,7 +104,7 @@ public class LocalConfigInfoProcessor {
try {
IOUtils.delete(file);
} catch (IOException ioe) {
log.error(envName, "NACOS-XXXX", "delete snapshot error, " + file + ", " + ioe.toString());
LOGGER.error("[" + envName + "] delete snapshot error, " + file, ioe);
}
} else {
try {
@ -108,7 +112,7 @@ public class LocalConfigInfoProcessor {
if (!parentFile.exists()) {
boolean isMdOk = parentFile.mkdirs();
if (!isMdOk) {
log.error(envName, "NACOS-XXXX", "save snapshot error");
LOGGER.error("[{}] save snapshot error", envName);
}
}
@ -119,7 +123,7 @@ public class LocalConfigInfoProcessor {
IOUtils.writeStringToFile(file, config, Constants.ENCODE);
}
} catch (IOException ioe) {
log.error(envName, "NACOS-XXXX", "save snapshot error, " + file + ", " + ioe.toString());
LOGGER.error("[" + envName + "] save snapshot error, " + file, ioe);
}
}
}
@ -140,7 +144,7 @@ public class LocalConfigInfoProcessor {
}
}
} catch (IOException ioe) {
log.error("NACOS-XXXX", "clean all snapshot error, " + ioe.toString(), ioe);
LOGGER.error("clean all snapshot error, " + ioe.toString(), ioe);
}
}
@ -149,9 +153,9 @@ public class LocalConfigInfoProcessor {
tmp = new File(tmp, "snapshot");
try {
IOUtils.cleanDirectory(tmp);
log.info("success delete " + envName + "-snapshot");
LOGGER.info("success delete " + envName + "-snapshot");
} catch (IOException e) {
log.info("fail delete " + envName + "-snapshot, " + e.toString());
LOGGER.info("fail delete " + envName + "-snapshot, " + e.toString());
e.printStackTrace();
}
}
@ -188,7 +192,7 @@ public class LocalConfigInfoProcessor {
+ "nacos" + File.separator + "config";
LOCAL_SNAPSHOT_PATH = System.getProperty("JM.SNAPSHOT.PATH", System.getProperty("user.home")) + File.separator
+ "nacos" + File.separator + "config";
log.warn("LOCAL_SNAPSHOT_PATH:{}", LOCAL_SNAPSHOT_PATH);
LOGGER.info("LOCAL_SNAPSHOT_PATH:{}", LOCAL_SNAPSHOT_PATH);
}
}

View File

@ -15,6 +15,18 @@
*/
package com.alibaba.nacos.client.config.impl;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.impl.EventDispatcher.ServerlistChangeEvent;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult;
import com.alibaba.nacos.client.config.utils.IOUtils;
import com.alibaba.nacos.client.utils.EnvUtil;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.StringReader;
import java.net.HttpURLConnection;
@ -26,20 +38,6 @@ import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.impl.EventDispatcher.ServerlistChangeEvent;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult;
import com.alibaba.nacos.client.config.utils.IOUtils;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.utils.EnvUtil;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Serverlist Manager
*
@ -47,7 +45,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
*/
public class ServerListManager {
final static public Logger log = LogUtils.logger(ServerListManager.class);
private static final Logger LOGGER = LogUtils.logger(ServerListManager.class);
public ServerListManager() {
isFixed = false;
@ -186,14 +184,13 @@ public class ServerListManager {
try {
this.wait((i + 1) * 100L);
} catch (Exception e) {
log.warn("get serverlist fail,url: " + addressServerUrl);
LOGGER.warn("get serverlist fail,url: {}", addressServerUrl);
}
}
if (serverUrls.isEmpty()) {
log.error("NACOS-0008", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0008", "环境问题",
"fail to get NACOS-server serverlist! env:" + name + ", not connnect url:" + addressServerUrl));
log.error(name, "NACOS-XXXX", "[init-serverlist] fail to get NACOS-server serverlist!");
LOGGER.error("[init-serverlist] fail to get NACOS-server serverlist! env: {}, url: {}", name,
addressServerUrl);
throw new NacosException(NacosException.SERVER_ERROR,
"fail to get NACOS-server serverlist! env:" + name + ", not connnect url:" + addressServerUrl);
}
@ -204,7 +201,7 @@ public class ServerListManager {
Iterator<String> iterator() {
if (serverUrls.isEmpty()) {
log.error(name, "NACOS-XXXX", "[iterator-serverlist] No server address defined!");
LOGGER.error("[{}] [iterator-serverlist] No server address defined!", name);
}
return new ServerAddressIterator(serverUrls);
}
@ -224,7 +221,7 @@ public class ServerListManager {
try {
updateIfChanged(getApacheServerList(url, name));
} catch (Exception e) {
log.error(name, "NACOS-XXXX", "[update-serverlist] failed to update serverlist from address server!",
LOGGER.error("[" + name + "][update-serverlist] failed to update serverlist from address server!",
e);
}
}
@ -232,10 +229,7 @@ public class ServerListManager {
private void updateIfChanged(List<String> newList) {
if (null == newList || newList.isEmpty()) {
log.warn("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题",
"[update-serverlist] current serverlist from address server is empty!!!"));
log.warn(name, "[update-serverlist] current serverlist from address server is empty!!!");
LOGGER.warn("[update-serverlist] current serverlist from address server is empty!!!");
return;
}
/**
@ -248,7 +242,7 @@ public class ServerListManager {
currentServerAddr = iterator().next();
EventDispatcher.fireEvent(new ServerlistChangeEvent());
log.info(name, "[update-serverlist] serverlist updated to {}", serverUrls);
LOGGER.info("[{}] [update-serverlist] serverlist updated to {}", name, serverUrls);
}
private List<String> getApacheServerList(String url, String name) {
@ -276,12 +270,12 @@ public class ServerListManager {
}
return result;
} else {
log.error(addressServerUrl, "NACOS-XXXX", "[check-serverlist] error. code={}", httpResult.code);
LOGGER.error("[check-serverlist] error. addressServerUrl: {}, code: {}", addressServerUrl,
httpResult.code);
return null;
}
} catch (IOException e) {
log.error("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题", e.toString()));
log.error(addressServerUrl, "NACOS-XXXX", "[check-serverlist] exception. msg={}", e.toString(), e);
LOGGER.error("[check-serverlist] exception. url: " + url, e);
return null;
}
}

View File

@ -16,9 +16,9 @@
package com.alibaba.nacos.client.config.listener.impl;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.StringUtils;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.StringReader;
@ -31,7 +31,8 @@ import java.util.Properties;
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class PropertiesListener extends AbstractListener {
final static public Logger log = LogUtils.logger(PropertiesListener.class);
private static final Logger LOGGER = LogUtils.logger(PropertiesListener.class);
@Override
public void receiveConfigInfo(String configInfo) {
@ -44,7 +45,7 @@ public abstract class PropertiesListener extends AbstractListener {
properties.load(new StringReader(configInfo));
innerReceive(properties);
} catch (IOException e) {
log.error("NACOS-XXXX", "load properties error" + configInfo, e);
LOGGER.error("load properties error" + configInfo, e);
}
}

View File

@ -15,7 +15,8 @@
*/
package com.alibaba.nacos.client.config.utils;
import com.alibaba.nacos.client.logger.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
@ -71,13 +72,13 @@ public class ConcurrentDiskUtil {
} catch (Exception e) {
++i;
if (i > RETRY_COUNT) {
log.error("read {} fail;retryed time:{}",
LOGGER.error("read {} fail;retryed time:{}",
file.getName(), i);
throw new IOException("read " + file.getAbsolutePath()
+ " conflict");
}
sleep(SLEEP_BASETIME * i);
log.warn("read {} conflict;retry time:{}", file.getName(),
LOGGER.warn("read {} conflict;retry time:{}", file.getName(),
i);
}
} while (null == rlock);
@ -143,13 +144,13 @@ public class ConcurrentDiskUtil {
} catch (Exception e) {
++i;
if (i > RETRY_COUNT) {
log.error("write {} fail;retryed time:{}",
LOGGER.error("write {} fail;retryed time:{}",
file.getName(), i);
throw new IOException("write " + file.getAbsolutePath()
+ " conflict");
}
sleep(SLEEP_BASETIME * i);
log.warn("write {} conflict;retry time:{}", file.getName(),
LOGGER.warn("write {} conflict;retry time:{}", file.getName(),
i);
}
} while (null == lock);
@ -168,7 +169,7 @@ public class ConcurrentDiskUtil {
lock.release();
lock = null;
} catch (IOException e) {
log.warn("close wrong", e);
LOGGER.warn("close wrong", e);
}
}
if (channel != null) {
@ -176,7 +177,7 @@ public class ConcurrentDiskUtil {
channel.close();
channel = null;
} catch (IOException e) {
log.warn("close wrong", e);
LOGGER.warn("close wrong", e);
}
}
if (raf != null) {
@ -184,7 +185,7 @@ public class ConcurrentDiskUtil {
raf.close();
raf = null;
} catch (IOException e) {
log.warn("close wrong", e);
LOGGER.warn("close wrong", e);
}
}
@ -215,11 +216,11 @@ public class ConcurrentDiskUtil {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
log.warn("sleep wrong", e);
LOGGER.warn("sleep wrong", e);
}
}
static final public Logger log = LogUtils.logger(ConcurrentDiskUtil.class);
private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentDiskUtil.class);
static final int RETRY_COUNT = 10;
/**
* ms

View File

@ -15,7 +15,8 @@
*/
package com.alibaba.nacos.client.config.utils;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.utils.LogUtils;
import org.slf4j.Logger;
/**
* Get jvm config
@ -36,13 +37,13 @@ public class JVMUtil {
private static Boolean isMultiInstance = false;
private static String TRUE = "true";
static final public Logger log = LogUtils.logger(JVMUtil.class);
private static final Logger LOGGER = LogUtils.logger(JVMUtil.class);
static {
String multiDeploy = System.getProperty("isMultiInstance", "false");
if (TRUE.equals(multiDeploy)) {
isMultiInstance = true;
}
log.info("isMultiInstance:{}", isMultiInstance);
LOGGER.info("isMultiInstance:{}", isMultiInstance);
}
}

View File

@ -1,59 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.config.utils;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.logger.Level;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.LoggerFactory;
/**
* Log Util
*
* @author Nacos
*/
public class LogUtils {
static int JM_LOG_RETAIN_COUNT = 7;
static String JM_LOG_FILE_SIZE = "10MB";
static {
String tmp = "7";
try {
/**
* change timeout from 100 to 200
*/
tmp = System.getProperty("JM.LOG.RETAIN.COUNT", "7");
JM_LOG_RETAIN_COUNT = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
e.printStackTrace();
throw e;
}
JM_LOG_FILE_SIZE = System.getProperty("JM.LOG.FILE.SIZE", "10MB");
// logger init
Logger logger = LoggerFactory.getLogger("com.alibaba.nacos.client.config");
logger.setLevel(Level.INFO);
logger.setAdditivity(false);
logger.activateAppenderWithSizeRolling("nacos", "config.log", Constants.ENCODE, JM_LOG_FILE_SIZE,
JM_LOG_RETAIN_COUNT);
}
public static Logger logger(Class<?> clazz) {
return LoggerFactory.getLogger(clazz);
}
}

View File

@ -15,9 +15,9 @@
*/
package com.alibaba.nacos.client.identify;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.StringUtils;
import org.slf4j.Logger;
import java.util.concurrent.ConcurrentHashMap;
@ -27,7 +27,8 @@ import java.util.concurrent.ConcurrentHashMap;
* @author Nacos
*/
public final class CredentialService implements SpasCredentialLoader {
static final public Logger log = LogUtils.logger(CredentialService.class);
private static final Logger LOGGER = LogUtils.logger(CredentialService.class);
private static ConcurrentHashMap<String, CredentialService> instances
= new ConcurrentHashMap<String, CredentialService>();
@ -81,7 +82,7 @@ public final class CredentialService implements SpasCredentialLoader {
if (watcher != null) {
watcher.stop();
}
log.info(appName, this.getClass().getSimpleName() + " is freed");
LOGGER.info("[{}] {} is freed", appName, this.getClass().getSimpleName());
}
public Credentials getCredential() {

View File

@ -15,6 +15,10 @@
*/
package com.alibaba.nacos.client.identify;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.StringUtils;
import org.slf4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@ -25,17 +29,13 @@ import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.utils.StringUtils;
/**
* Credential Watcher
*
* @author Nacos
*/
public class CredentialWatcher {
static final public Logger SpasLogger = LogUtils.logger(CredentialWatcher.class);
private static final Logger SpasLogger = LogUtils.logger(CredentialWatcher.class);
private static final long REFRESH_INTERVAL = 10 * 1000;
private CredentialService serviceInstance;
@ -92,7 +92,7 @@ public class CredentialWatcher {
stopped = true;
}
}
SpasLogger.info(appName, this.getClass().getSimpleName() + " is stopped");
SpasLogger.info("[{}] {} is stopped", appName, this.getClass().getSimpleName());
}
private void loadCredential(boolean init) {
@ -113,12 +113,13 @@ public class CredentialWatcher {
: appName);
} else {
if (logWarn) {
SpasLogger.info(appName, "Defined credential file: -D" + "spas.identity" + "=" + propertyPath);
SpasLogger.info("[{}] Defined credential file: -Dspas.identity={}", appName, propertyPath);
}
}
} else {
if (logWarn) {
SpasLogger.info(appName, "Load credential file from classpath: " + Constants.PROPERTIES_FILENAME);
SpasLogger.info("[{}] Load credential file from classpath: {}", appName,
Constants.PROPERTIES_FILENAME);
}
}
}
@ -149,7 +150,7 @@ public class CredentialWatcher {
secretKey = System.getenv(Constants.ENV_SECRET_KEY);
if (accessKey == null && secretKey == null) {
if (logWarn) {
SpasLogger.info(appName, "No credential found");
SpasLogger.info("{} No credential found", appName);
}
return;
}
@ -158,7 +159,7 @@ public class CredentialWatcher {
try {
properties.load(propertiesIS);
} catch (IOException e) {
SpasLogger.error("26", "Unable to load credential file, appName:" + appName
SpasLogger.error("[26] Unable to load credential file, appName:" + appName
+ "Unable to load credential file " + propertyPath, e);
propertyPath = null;
return;
@ -166,13 +167,13 @@ public class CredentialWatcher {
try {
propertiesIS.close();
} catch (IOException e) {
SpasLogger.error("27", "Unable to close credential file, appName:" + appName
SpasLogger.error("[27] Unable to close credential file, appName:" + appName
+ "Unable to close credential file " + propertyPath, e);
}
}
if (logWarn) {
SpasLogger.info(appName, "Load credential file " + propertyPath);
SpasLogger.info("[{}] Load credential file {}", appName, propertyPath);
}
if (!Constants.DOCKER_CREDENTIAL_PATH.equals(propertyPath)) {
@ -201,8 +202,8 @@ public class CredentialWatcher {
Credentials credential = new Credentials(accessKey, secretKey);
if (!credential.valid()) {
SpasLogger.warn("1", "Credential file missing required property" + appName + "Credential file missing "
+ Constants.ACCESS_KEY + " or " + Constants.SECRET_KEY);
SpasLogger.warn("[1] Credential file missing required property {} Credential file missing {} or {}",
appName, Constants.ACCESS_KEY, Constants.SECRET_KEY);
propertyPath = null;
// return;
}

View File

@ -1,52 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger;
/**
* 阿里中间件日志级别
*
* @author zhuyong 2014年3月20日 上午9:57:27
*/
public enum Level {
/**
* log level
*/
DEBUG("DEBUG"),
INFO("INFO"),
WARN("WARN"),
ERROR("ERROR"),
OFF("OFF");
private String name;
Level(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public static Level codeOf(String level) {
for (Level l : Level.values()) {
if (l.name.equals(level)) {
return l;
}
}
return OFF;
}
}

View File

@ -1,241 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger;
import com.alibaba.nacos.client.logger.option.ActivateOption;
/**
* <pre>
* 阿里中间件日志API用于输出定制化的日志
*
* 定制格式如下01 %d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n
* 其中
* 01 日志API版本后续如果格式有变化会修改此版本号方便机器解析
* d{yyyy-MM-dd HH:mm:ss.SSS} 时间2014-03-19 20:55:08.501最后面的表示毫秒
* %p 日志级别如INFO,ERROR
* [%-5t:%c{2}] 线程名:日志名
* %m 日志信息
* %n 换行
*
* 关于%m也有其中的格式要求[Context] [STAT-INFO] [ERROR-CODE]
* 其中
* Context 打印时间时的上下文信息如果没有则内容为空'[]'这个占位符仍要输出
* STAT-INFO 待定
* ERROR-CODE 常见的错误码帮助用户解决问题
*
* 在异常中也需要输出ErrorCode及对应的TraceUrl可以使用
* com.alibaba.nacos.client.logger.support.LoggerHelper.getErrorCodeStr(String errorCode)来获取格式化后的串
* </pre>
*
* @author zhuyong 2014年3月20日 上午9:58:27
*/
public interface Logger extends ActivateOption {
/**
* 输出Debug日志
*
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
*/
void debug(String message);
/**
* 输出Debug日志
*
* @param format 日志信息格式化字符串比如 'Hi,{} {} {}'当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param args 格式化串参数数组
*/
void debug(String format, Object... args);
/**
* 输出Debug日志
*
* @param context 日志上下文信息
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
*/
void debug(String context, String message);
/**
* 输出Debug日志
*
* @param context 日志上下文信息
* @param format 日志信息格式化字符串比如 'Hi,{} {} {}'当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param args 格式化串参数数组
*/
void debug(String context, String format, Object... args);
/**
* 输出Info日志
*
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
*/
void info(String message);
/**
* 输出Info日志
*
* @param format 日志信息格式化字符串比如 'Hi,{} {} {}'当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param args 格式化串参数数组
*/
void info(String format, Object... args);
/**
* 输出Info日志
*
* @param context 日志上下文信息
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
*/
void info(String context, String message);
/**
* 输出Info日志
*
* @param context 日志上下文信息
* @param format 日志信息格式化字符串比如 'Hi,{} {} {}'当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param args 格式化串参数数组
*/
void info(String context, String format, Object... args);
/**
* 输出Warn日志
*
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
*/
void warn(String message);
/**
* 输出Warn日志
*
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param t 异常信息
* @since 0.1.5
*/
void warn(String message, Throwable t);
/**
* 输出Warn日志
*
* @param format 日志信息格式化字符串比如 'Hi,{} {} {}'当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param args 格式化串参数数组
*/
void warn(String format, Object... args);
/**
* 输出Warn日志
*
* @param context 日志上下文信息
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
*/
void warn(String context, String message);
/**
* 输出Warn日志
*
* @param context 日志上下文信息
* @param format 日志信息格式化字符串比如 'Hi,{} {} {}'当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param args 格式化串参数数组
*/
void warn(String context, String format, Object... args);
/**
* 输出Error日志
*
* @param errorCode 错误码如HSF-0001
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
*/
void error(String errorCode, String message);
/**
* 输出Error日志
*
* @param errorCode 错误码如HSF-0001
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param t 异常信息
*/
void error(String errorCode, String message, Throwable t);
/**
* 输出Error日志
*
* @param errorCode 错误码如HSF-0001
* @param format 日志信息格式化字符串比如 'Hi,{} {} {}'当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param objs 格式化串参数数组
*/
void error(String errorCode, String format, Object... objs);
/**
* 输出Error日志
*
* @param context 日志上下文信息
* @param errorCode 错误码
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
*/
void error(String context, String errorCode, String message);
/**
* 输出Error日志
*
* @param context 日志上下文信息
* @param errorCode 错误码
* @param message 日志信息当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param t 异常信息
*/
void error(String context, String errorCode, String message, Throwable t);
/**
* 输出Error日志
*
* @param context 日志上下文信息
* @param errorCode 错误码
* @param format 日志信息格式化字符串比如 'Hi,{} {} {}'当使用ResourceBundle用于国际化日志输出时message为对应的key, since 0.1.5
* @param args 格式化串参数
*/
void error(String context, String errorCode, String format, Object... args);
/**
* 判断Debug级别是否开启
*
* @return Debug级别是否开启
*/
boolean isDebugEnabled();
/**
* 判断Info级别是否开启
*
* @return Info级别是否开启
*/
boolean isInfoEnabled();
/**
* 判断Warn级别是否开启
*
* @return Warn级别是否开启
*/
boolean isWarnEnabled();
/**
* 判断Error级别是否开启
*
* @return Error级别是否开启
*/
boolean isErrorEnabled();
/**
* * 获取内部日志实现对象
*
* @return 内部日志实现对象
*/
Object getDelegate();
}

View File

@ -1,94 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger;
import com.alibaba.nacos.client.logger.log4j2.Log4j2LoggerFactory;
import com.alibaba.nacos.client.logger.nop.NopLoggerFactory;
import com.alibaba.nacos.client.logger.slf4j.Slf4jLoggerFactory;
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
import com.alibaba.nacos.client.logger.support.LogLog;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* <pre>
* 阿里中间件LoggerFactory获取具体日志实现
* 目前支持log4j/log4j2/slf4j/jcl日志门面和log4j/log4j2/logback日志实现
* log4j
* log4j2
* slf4j + logback
* slf4j + slf4j-log4j12 + log4j
* slf4j + slf4j-log4j-impl + log4j2
* jcl + log4j
* jcl + jcl-over-slf4j + slf4j + logback
* jcl + jcl-over-slf4j + slf4j + slf4j-log4j-impl + log4j
* 查找实现的优先顺序依次为slf4j > log4j > log4j2
* </pre>
*
* @author zhuyong 2014年3月20日 上午10:17:33
*/
public class LoggerFactory {
private LoggerFactory() {
}
private static volatile ILoggerFactory LOGGER_FACTORY;
private static Map<String, Logger> loggerCache;
// 查找常用的日志框架
static {
try {
setLoggerFactory(new Slf4jLoggerFactory());
LogLog.info("Init JM logger with Slf4jLoggerFactory success, " + LoggerFactory.class.getClassLoader());
} catch (Throwable e1) {
try {
setLoggerFactory(new Log4j2LoggerFactory());
LogLog.info("Init JM logger with Log4j2LoggerFactory, " + LoggerFactory.class.getClassLoader());
} catch (Throwable e2) {
setLoggerFactory(new NopLoggerFactory());
LogLog.warn("Init JM logger with NopLoggerFactory, pay attention. "
+ LoggerFactory.class.getClassLoader(), e2);
}
}
loggerCache = new ConcurrentHashMap<String, Logger>();
}
public static Logger getLogger(String name) {
Logger logger = loggerCache.get(name);
if (logger == null) {
synchronized (LOGGER_FACTORY) {
logger = loggerCache.get(name);
if (logger == null) {
logger = LOGGER_FACTORY.getLogger(name);
loggerCache.put(name, logger);
}
}
}
return logger;
}
public static Logger getLogger(Class<?> clazz) {
return getLogger(clazz.getName());
}
private static void setLoggerFactory(ILoggerFactory loggerFactory) {
if (loggerFactory != null) {
LoggerFactory.LOGGER_FACTORY = loggerFactory;
}
}
}

View File

@ -1,394 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
/*
* $Id: JSONArray.java,v 1.1 2006/04/15 14:10:48 platform Exp $
* Created on 2006-4-10
*/
package com.alibaba.nacos.client.logger.json;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* A JSON array. JSONObject supports java.util.List interface.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
private static final long serialVersionUID = 3957988303675231981L;
/**
* Constructs an empty JSONArray.
*/
public JSONArray() {
super();
}
/**
* Constructs a JSONArray containing the elements of the specified collection, in the order they are returned by the
* collection's iterator.
*
* @param c the collection whose elements are to be placed into this JSONArray
*/
public JSONArray(Collection c) {
super(c);
}
/**
* Encode a list into JSON text and write it to out. If this list is also a JSONStreamAware or a JSONAware,
* JSONStreamAware and JSONAware specific behaviours will be ignored at this top level.
*
* @param collection
* @param out
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
*/
public static void writeJSONString(Collection collection, Writer out) throws IOException {
if (collection == null) {
out.write("null");
return;
}
boolean first = true;
Iterator iter = collection.iterator();
out.write('[');
while (iter.hasNext()) {
if (first) {
first = false;
} else {
out.write(',');
}
Object value = iter.next();
if (value == null) {
out.write("null");
continue;
}
JSONValue.writeJSONString(value, out);
}
out.write(']');
}
public void writeJSONString(Writer out) throws IOException {
writeJSONString(this, out);
}
/**
* Convert a list to JSON text. The result is a JSON array. If this list is also a JSONAware, JSONAware specific
* behaviours will be omitted at this top level.
*
* @param collection
* @return JSON text, or "null" if list is null.
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
*/
public static String toJSONString(Collection collection) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(collection, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(byte[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
out.write("]");
}
}
public static String toJSONString(byte[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(short[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
out.write("]");
}
}
public static String toJSONString(short[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(int[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
out.write("]");
}
}
public static String toJSONString(int[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(long[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
out.write("]");
}
}
public static String toJSONString(long[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(float[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
out.write("]");
}
}
public static String toJSONString(float[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(double[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
out.write("]");
}
}
public static String toJSONString(double[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(boolean[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
out.write("]");
}
}
public static String toJSONString(boolean[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(char[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[\"");
out.write(String.valueOf(array[0]));
for (int i = 1; i < array.length; i++) {
out.write("\",\"");
out.write(String.valueOf(array[i]));
}
out.write("\"]");
}
}
public static String toJSONString(char[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(Object[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
JSONValue.writeJSONString(array[0], out);
for (int i = 1; i < array.length; i++) {
out.write(",");
JSONValue.writeJSONString(array[i], out);
}
out.write("]");
}
}
public static String toJSONString(Object[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public String toJSONString() {
return toJSONString(this);
}
/**
* Returns a string representation of this array. This is equivalent to calling {@link JSONArray#toJSONString()}.
*/
public String toString() {
return toJSONString();
}
}

View File

@ -1,31 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.json;
/**
* Beans that support customized output of JSON text shall implement this interface.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public interface JSONAware {
/**
* format change
*
* @return JSON text
*/
String toJSONString();
}

View File

@ -1,145 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
/*
* $Id: JSONObject.java,v 1.1 2006/04/15 14:10:48 platform Exp $
* Created on 2006-4-10
*/
package com.alibaba.nacos.client.logger.json;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware {
private static final long serialVersionUID = -503443796854799292L;
public JSONObject() {
super();
}
/**
* Allows creation of a JSONObject from a Map. After that, both the generated JSONObject and the Map can be modified
* independently.
*
* @param map
*/
public JSONObject(Map map) {
super(map);
}
/**
* Encode a map into JSON text and write it to out. If this map is also a JSONAware or JSONStreamAware, JSONAware or
* JSONStreamAware specific behaviours will be ignored at this top level.
*
* @param map
* @param out
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
*/
public static void writeJSONString(Map map, Writer out) throws IOException {
if (map == null) {
out.write("null");
return;
}
boolean first = true;
Iterator iter = map.entrySet().iterator();
out.write('{');
while (iter.hasNext()) {
if (first) {
first = false;
} else {
out.write(',');
}
Map.Entry entry = (Map.Entry)iter.next();
out.write('\"');
out.write(escape(String.valueOf(entry.getKey())));
out.write('\"');
out.write(':');
JSONValue.writeJSONString(entry.getValue(), out);
}
out.write('}');
}
public void writeJSONString(Writer out) throws IOException {
writeJSONString(this, out);
}
/**
* Convert a map to JSON text. The result is a JSON object. If this map is also a JSONAware, JSONAware specific
* behaviours will be omitted at this top level.
*
* @param map
* @return JSON text, or "null" if map is null.
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
*/
public static String toJSONString(Map map) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(map, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen with a StringWriter
throw new RuntimeException(e);
}
}
public String toJSONString() {
return toJSONString(this);
}
public String toString() {
return toJSONString();
}
public static String toString(String key, Object value) {
StringBuffer sb = new StringBuffer();
sb.append('\"');
if (key == null) {
sb.append("null");
} else {
JSONValue.escape(key, sb);
}
sb.append('\"').append(':');
sb.append(JSONValue.toJSONString(value));
return sb.toString();
}
/**
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). It's the same as
* JSONValue.escape() only for compatibility here.
*
* @param s
* @return
* @see com.alibaba.nacos.client.logger.json.JSONValue#escape(String)
*/
public static String escape(String s) {
return JSONValue.escape(s);
}
}

View File

@ -1,35 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.json;
import java.io.IOException;
import java.io.Writer;
/**
* Beans that support customized output of JSON text to a writer shall implement this interface.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public interface JSONStreamAware {
/**
* write JSON string to out.
*
* @param out out writer
* @throws IOException Exception
*/
void writeJSONString(Writer out) throws IOException;
}

View File

@ -1,315 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
/*
* $Id: JSONValue.java,v 1.1 2006/04/15 14:37:04 platform Exp $
* Created on 2006-4-15
*/
package com.alibaba.nacos.client.logger.json;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import com.alibaba.nacos.client.logger.json.parser.JSONParser;
import com.alibaba.nacos.client.logger.json.parser.ParseException;
/**
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JSONValue {
/**
* Parse JSON text into java object from the input source. Please use parseWithException() if you don't want to
* ignore the exception.
*
* @param in
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
* @see #parseWithException(Reader)
* @deprecated this method may throw an {@code Error} instead of returning {@code null}; please use {@link
* JSONValue#parseWithException(Reader)} instead
*/
public static Object parse(Reader in) {
try {
JSONParser parser = new JSONParser();
return parser.parse(in);
} catch (Exception e) {
return null;
}
}
/**
* Parse JSON text into java object from the given string. Please use parseWithException() if you don't want to
* ignore the exception.
*
* @param s
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
* @see #parseWithException(Reader)
* @deprecated this method may throw an {@code Error} instead of returning {@code null}; please use {@link
* JSONValue#parseWithException(String)} instead
*/
public static Object parse(String s) {
StringReader in = new StringReader(s);
return parse(in);
}
/**
* Parse JSON text into java object from the input source.
*
* @param in
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
* @throws IOException
* @throws ParseException
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser
*/
public static Object parseWithException(Reader in) throws IOException, ParseException {
JSONParser parser = new JSONParser();
return parser.parse(in);
}
public static Object parseWithException(String s) throws ParseException {
JSONParser parser = new JSONParser();
return parser.parse(s);
}
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware
* will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or
* List) with "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or
* JSONArray.writeJSONString(List, Writer) instead.
*
* @param value
* @param writer
* @see com.alibaba.nacos.client.logger.jsonJSONObject#writeJSONString(Map, Writer)
* @see com.alibaba.nacos.client.logger.jsonJSONArray#writeJSONString(List, Writer)
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if (value == null) {
out.write("null");
return;
}
if (value instanceof String) {
out.write('\"');
out.write(escape((String)value));
out.write('\"');
return;
}
if (value instanceof Double) {
if (((Double)value).isInfinite() || ((Double)value).isNaN()) {
out.write("null");
} else {
out.write(value.toString());
}
return;
}
if (value instanceof Float) {
if (((Float)value).isInfinite() || ((Float)value).isNaN()) {
out.write("null");
} else {
out.write(value.toString());
}
return;
}
if (value instanceof Number) {
out.write(value.toString());
return;
}
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware)value).writeJSONString(out);
return;
}
if ((value instanceof JSONAware)) {
out.write(((JSONAware)value).toJSONString());
return;
}
if (value instanceof Map) {
JSONObject.writeJSONString((Map)value, out);
return;
}
if (value instanceof Collection) {
JSONArray.writeJSONString((Collection)value, out);
return;
}
if (value instanceof byte[]) {
JSONArray.writeJSONString((byte[])value, out);
return;
}
if (value instanceof short[]) {
JSONArray.writeJSONString((short[])value, out);
return;
}
if (value instanceof int[]) {
JSONArray.writeJSONString((int[])value, out);
return;
}
if (value instanceof long[]) {
JSONArray.writeJSONString((long[])value, out);
return;
}
if (value instanceof float[]) {
JSONArray.writeJSONString((float[])value, out);
return;
}
if (value instanceof double[]) {
JSONArray.writeJSONString((double[])value, out);
return;
}
if (value instanceof boolean[]) {
JSONArray.writeJSONString((boolean[])value, out);
return;
}
if (value instanceof char[]) {
JSONArray.writeJSONString((char[])value, out);
return;
}
if (value instanceof Object[]) {
JSONArray.writeJSONString((Object[])value, out);
return;
}
out.write(value.toString());
}
/**
* Convert an object to JSON text.
* <p>
* If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly.
* <p>
* DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with "this"
* as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead.
*
* @param value
* @return JSON text, or "null" if value is null or it's an NaN or an INF number.
* @see com.alibaba.nacos.client.logger.json.JSONObject#toJSONString(Map)
*/
public static String toJSONString(Object value) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(value, writer);
return writer.toString();
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
/**
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
*
* @param s
* @return
*/
public static String escape(String s) {
if (s == null) {
return null;
}
StringBuffer sb = new StringBuffer();
escape(s, sb);
return sb.toString();
}
/**
* @param s - Must not be null.
* @param sb
*/
static void escape(String s, StringBuffer sb) {
final int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
//Reference: http://www.unicode.org/versions/Unicode5.1.0/
if (isUnicodeChar(ch)) {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < FOUR - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
}
}//for
}
private static boolean isUnicodeChar(char ch) {
return (ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F')
|| (ch >= '\u2000' && ch <= '\u20FF');
}
private static int FOUR = 4;
}

View File

@ -1,43 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.json.parser;
import java.util.List;
import java.util.Map;
/**
* Container factory for creating containers for JSON object and JSON array.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#parse(java.io.Reader, ContainerFactory)
*/
public interface ContainerFactory {
/**
* create json container
*
* @return A Map instance to store JSON object, or null if you want to use com.alibaba.nacos.client.logger
* .jsonJSONObject.
*/
Map createObjectContainer();
/**
* create array json container
*
* @return A List instance to store JSON array, or null if you want to use com.alibaba.nacos.client.logger
* .jsonJSONArray.
*/
List creatArrayContainer();
}

View File

@ -1,117 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.json.parser;
import java.io.IOException;
/**
* A simplified and stoppable SAX-like content handler for stream processing of JSON text.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
* @see org.xml.sax.ContentHandler
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#parse(java.io.Reader, ContentHandler, boolean)
*/
public interface ContentHandler {
/**
* Receive notification of the beginning of JSON processing. The parser will invoke this method only once.
*
* @throws ParseException - JSONParser will stop and throw the same exception to the caller when receiving this
* exception.
* @throws IOException
*/
void startJSON() throws ParseException, IOException;
/**
* Receive notification of the end of JSON processing.
*
* @throws ParseException
* @throws IOException
*/
void endJSON() throws ParseException, IOException;
/**
* Receive notification of the beginning of a JSON object.
*
* @return false if the handler wants to stop parsing after return.
* @throws ParseException - JSONParser will stop and throw the same exception to the caller when receiving this
* exception.
* @throws IOException
* @see #endJSON
*/
boolean startObject() throws ParseException, IOException;
/**
* Receive notification of the end of a JSON object.
*
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* @throws IOException
* @see #startObject
*/
boolean endObject() throws ParseException, IOException;
/**
* Receive notification of the beginning of a JSON object entry.
*
* @param key - Key of a JSON object entry.
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* @throws IOException
* @see #endObjectEntry
*/
boolean startObjectEntry(String key) throws ParseException, IOException;
/**
* Receive notification of the end of the value of previous object entry.
*
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* @throws IOException
* @see #startObjectEntry
*/
boolean endObjectEntry() throws ParseException, IOException;
/**
* Receive notification of the beginning of a JSON array.
*
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* @throws IOException
* @see #endArray
*/
boolean startArray() throws ParseException, IOException;
/**
* Receive notification of the end of a JSON array.
*
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* @throws IOException
* @see #startArray
*/
boolean endArray() throws ParseException, IOException;
/**
* Receive notification of the JSON primitive values: java.lang.String, java.lang.Number, java.lang.Boolean null
*
* @param value - Instance of the following: java.lang.String, java.lang.Number, java.lang.Boolean null
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* @throws IOException
*/
boolean primitive(Object value) throws ParseException, IOException;
}

View File

@ -1,548 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
/*
* $Id: JSONParser.java,v 1.1 2006/04/15 14:10:48 platform Exp $
* Created on 2006-4-15
*/
package com.alibaba.nacos.client.logger.json.parser;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.alibaba.nacos.client.logger.json.JSONArray;
import com.alibaba.nacos.client.logger.json.JSONObject;
/**
* Parser for JSON text. Please note that JSONParser is NOT thread-safe.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JSONParser {
public static final int S_INIT = 0;
public static final int S_IN_FINISHED_VALUE = 1;
public static final int S_IN_OBJECT = 2;
public static final int S_IN_ARRAY = 3;
public static final int S_PASSED_PAIR_KEY = 4;
public static final int S_IN_PAIR_VALUE = 5;
public static final int S_END = 6;
public static final int S_IN_ERROR = -1;
private LinkedList handlerStatusStack;
private Yylex lexer = new Yylex((Reader)null);
private Yytoken token = null;
private int status = S_INIT;
private int peekStatus(LinkedList statusStack) {
if (statusStack.size() == 0) {
return -1;
}
Integer status = (Integer)statusStack.getFirst();
return status.intValue();
}
/**
* Reset the parser to the initial state without resetting the underlying reader.
*/
public void reset() {
token = null;
status = S_INIT;
handlerStatusStack = null;
}
/**
* Reset the parser to the initial state with a new character reader.
*
* @param in - The new character reader.
* @throws IOException
* @throws ParseException
*/
public void reset(Reader in) {
lexer.yyreset(in);
reset();
}
/**
* @return The position of the beginning of the current token.
*/
public int getPosition() {
return lexer.getPosition();
}
public Object parse(String s) throws ParseException {
return parse(s, (ContainerFactory)null);
}
public Object parse(String s, ContainerFactory containerFactory) throws ParseException {
StringReader in = new StringReader(s);
try {
return parse(in, containerFactory);
} catch (IOException ie) {
/*
* Actually it will never happen.
*/
throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie);
}
}
public Object parse(Reader in) throws IOException, ParseException {
return parse(in, (ContainerFactory)null);
}
/**
* Parse JSON text into java object from the input source.
*
* @param in
* @param containerFactory - Use this factory to createyour own JSON object and JSON array containers.
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
* @throws IOException
* @throws ParseException
*/
public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException {
reset(in);
LinkedList statusStack = new LinkedList();
LinkedList valueStack = new LinkedList();
try {
do {
nextToken();
switch (status) {
case S_INIT:
switch (token.type) {
case Yytoken.TYPE_VALUE:
status = S_IN_FINISHED_VALUE;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(token.value);
break;
case Yytoken.TYPE_LEFT_BRACE:
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(createObjectContainer(containerFactory));
break;
case Yytoken.TYPE_LEFT_SQUARE:
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(createArrayContainer(containerFactory));
break;
default:
status = S_IN_ERROR;
}//inner switch
break;
case S_IN_FINISHED_VALUE:
if (token.type == Yytoken.TYPE_EOF) {
return valueStack.removeFirst();
} else {
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
case S_IN_OBJECT:
switch (token.type) {
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if (token.value instanceof String) {
String key = (String)token.value;
valueStack.addFirst(key);
status = S_PASSED_PAIR_KEY;
statusStack.addFirst(Integer.valueOf(status));
} else {
status = S_IN_ERROR;
}
break;
case Yytoken.TYPE_RIGHT_BRACE:
if (valueStack.size() > 1) {
statusStack.removeFirst();
valueStack.removeFirst();
status = peekStatus(statusStack);
} else {
status = S_IN_FINISHED_VALUE;
}
break;
default:
status = S_IN_ERROR;
break;
}//inner switch
break;
case S_PASSED_PAIR_KEY:
switch (token.type) {
case Yytoken.TYPE_COLON:
break;
case Yytoken.TYPE_VALUE:
statusStack.removeFirst();
String key = (String)valueStack.removeFirst();
Map parent = (Map)valueStack.getFirst();
parent.put(key, token.value);
status = peekStatus(statusStack);
break;
case Yytoken.TYPE_LEFT_SQUARE:
statusStack.removeFirst();
key = (String)valueStack.removeFirst();
parent = (Map)valueStack.getFirst();
List newArray = createArrayContainer(containerFactory);
parent.put(key, newArray);
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(newArray);
break;
case Yytoken.TYPE_LEFT_BRACE:
statusStack.removeFirst();
key = (String)valueStack.removeFirst();
parent = (Map)valueStack.getFirst();
Map newObject = createObjectContainer(containerFactory);
parent.put(key, newObject);
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(newObject);
break;
default:
status = S_IN_ERROR;
}
break;
case S_IN_ARRAY:
switch (token.type) {
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
List val = (List)valueStack.getFirst();
val.add(token.value);
break;
case Yytoken.TYPE_RIGHT_SQUARE:
if (valueStack.size() > 1) {
statusStack.removeFirst();
valueStack.removeFirst();
status = peekStatus(statusStack);
} else {
status = S_IN_FINISHED_VALUE;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
val = (List)valueStack.getFirst();
Map newObject = createObjectContainer(containerFactory);
val.add(newObject);
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(newObject);
break;
case Yytoken.TYPE_LEFT_SQUARE:
val = (List)valueStack.getFirst();
List newArray = createArrayContainer(containerFactory);
val.add(newArray);
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(newArray);
break;
default:
status = S_IN_ERROR;
}//inner switch
break;
case S_IN_ERROR:
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
default:
break;
}//switch
if (status == S_IN_ERROR) {
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
} while (token.type != Yytoken.TYPE_EOF);
} catch (IOException ie) {
throw ie;
}
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
private void nextToken() throws ParseException, IOException {
token = lexer.yylex();
if (token == null) {
token = new Yytoken(Yytoken.TYPE_EOF, null);
}
}
private Map createObjectContainer(ContainerFactory containerFactory) {
if (containerFactory == null) {
return new JSONObject();
}
Map m = containerFactory.createObjectContainer();
if (m == null) {
return new JSONObject();
}
return m;
}
private List createArrayContainer(ContainerFactory containerFactory) {
if (containerFactory == null) {
return new JSONArray();
}
List l = containerFactory.creatArrayContainer();
if (l == null) {
return new JSONArray();
}
return l;
}
public void parse(String s, ContentHandler contentHandler) throws ParseException {
parse(s, contentHandler, false);
}
public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException {
StringReader in = new StringReader(s);
try {
parse(in, contentHandler, isResume);
} catch (IOException ie) {
/*
* Actually it will never happen.
*/
throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie);
}
}
public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException {
parse(in, contentHandler, false);
}
/**
* Stream processing of JSON text.
*
* @param in
* @param contentHandler
* @param isResume - Indicates if it continues previous parsing operation. If set to true, resume parsing the
* old stream, and parameter 'in' will be ignored. If this method is called for the first time
* in this instance, isResume will be ignored.
* @throws IOException
* @throws ParseException
* @see ContentHandler
*/
public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException {
if (!isResume) {
reset(in);
handlerStatusStack = new LinkedList();
} else {
if (handlerStatusStack == null) {
isResume = false;
reset(in);
handlerStatusStack = new LinkedList();
}
}
LinkedList statusStack = handlerStatusStack;
try {
do {
switch (status) {
case S_INIT:
contentHandler.startJSON();
nextToken();
switch (token.type) {
case Yytoken.TYPE_VALUE:
status = S_IN_FINISHED_VALUE;
statusStack.addFirst(Integer.valueOf(status));
if (!contentHandler.primitive(token.value)) {
return;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
if (!contentHandler.startObject()) {
return;
}
break;
case Yytoken.TYPE_LEFT_SQUARE:
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
if (!contentHandler.startArray()) {
return;
}
break;
default:
status = S_IN_ERROR;
}//inner switch
break;
case S_IN_FINISHED_VALUE:
nextToken();
if (token.type == Yytoken.TYPE_EOF) {
contentHandler.endJSON();
status = S_END;
return;
} else {
status = S_IN_ERROR;
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
case S_IN_OBJECT:
nextToken();
switch (token.type) {
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if (token.value instanceof String) {
String key = (String)token.value;
status = S_PASSED_PAIR_KEY;
statusStack.addFirst(Integer.valueOf(status));
if (!contentHandler.startObjectEntry(key)) {
return;
}
} else {
status = S_IN_ERROR;
}
break;
case Yytoken.TYPE_RIGHT_BRACE:
if (statusStack.size() > 1) {
statusStack.removeFirst();
status = peekStatus(statusStack);
} else {
status = S_IN_FINISHED_VALUE;
}
if (!contentHandler.endObject()) {
return;
}
break;
default:
status = S_IN_ERROR;
break;
}//inner switch
break;
case S_PASSED_PAIR_KEY:
nextToken();
switch (token.type) {
case Yytoken.TYPE_COLON:
break;
case Yytoken.TYPE_VALUE:
statusStack.removeFirst();
status = peekStatus(statusStack);
if (!contentHandler.primitive(token.value)) {
return;
}
if (!contentHandler.endObjectEntry()) {
return;
}
break;
case Yytoken.TYPE_LEFT_SQUARE:
statusStack.removeFirst();
statusStack.addFirst(Integer.valueOf(S_IN_PAIR_VALUE));
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
if (!contentHandler.startArray()) {
return;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
statusStack.removeFirst();
statusStack.addFirst(Integer.valueOf(S_IN_PAIR_VALUE));
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
if (!contentHandler.startObject()) {
return;
}
break;
default:
status = S_IN_ERROR;
}
break;
case S_IN_PAIR_VALUE:
/*
* S_IN_PAIR_VALUE is just a marker to indicate the end of an object entry, it doesn't proccess any token,
* therefore delay consuming token until next round.
*/
statusStack.removeFirst();
status = peekStatus(statusStack);
if (!contentHandler.endObjectEntry()) {
return;
}
break;
case S_IN_ARRAY:
nextToken();
switch (token.type) {
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if (!contentHandler.primitive(token.value)) {
return;
}
break;
case Yytoken.TYPE_RIGHT_SQUARE:
if (statusStack.size() > 1) {
statusStack.removeFirst();
status = peekStatus(statusStack);
} else {
status = S_IN_FINISHED_VALUE;
}
if (!contentHandler.endArray()) {
return;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
if (!contentHandler.startObject()) {
return;
}
break;
case Yytoken.TYPE_LEFT_SQUARE:
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
if (!contentHandler.startArray()) {
return;
}
break;
default:
status = S_IN_ERROR;
}//inner switch
break;
case S_END:
return;
case S_IN_ERROR:
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
default:
break;
}//switch
if (status == S_IN_ERROR) {
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
} while (token.type != Yytoken.TYPE_EOF);
} catch (IOException ie) {
status = S_IN_ERROR;
throw ie;
} catch (ParseException pe) {
status = S_IN_ERROR;
throw pe;
} catch (RuntimeException re) {
status = S_IN_ERROR;
throw re;
} catch (Error e) {
status = S_IN_ERROR;
throw e;
}
status = S_IN_ERROR;
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
}

View File

@ -1,103 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.json.parser;
/**
* ParseException explains why and where the error occurs in source JSON text.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
public class ParseException extends Exception {
private static final long serialVersionUID = -7880698968187728547L;
public static final int ERROR_UNEXPECTED_CHAR = 0;
public static final int ERROR_UNEXPECTED_TOKEN = 1;
public static final int ERROR_UNEXPECTED_EXCEPTION = 2;
private int errorType;
private Object unexpectedObject;
private int position;
public ParseException(int errorType) {
this(-1, errorType, null);
}
public ParseException(int errorType, Object unexpectedObject) {
this(-1, errorType, unexpectedObject);
}
public ParseException(int position, int errorType, Object unexpectedObject) {
this.position = position;
this.errorType = errorType;
this.unexpectedObject = unexpectedObject;
}
public int getErrorType() {
return errorType;
}
public void setErrorType(int errorType) {
this.errorType = errorType;
}
/**
* @return The character position (starting with 0) of the input where the error occurs.
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#getPosition()
*/
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
/**
* @return One of the following base on the value of errorType: ERROR_UNEXPECTED_CHAR java.lang.Character
* ERROR_UNEXPECTED_TOKEN com.alibaba.nacos.client.logger.jsonparser.Yytoken ERROR_UNEXPECTED_EXCEPTION
* java.lang.Exception
* @see com.alibaba.nacos.client.logger.json.parser.Yytoken
*/
public Object getUnexpectedObject() {
return unexpectedObject;
}
public void setUnexpectedObject(Object unexpectedObject) {
this.unexpectedObject = unexpectedObject;
}
public String getMessage() {
StringBuffer sb = new StringBuffer();
switch (errorType) {
case ERROR_UNEXPECTED_CHAR:
sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position)
.append(".");
break;
case ERROR_UNEXPECTED_TOKEN:
sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append(
".");
break;
case ERROR_UNEXPECTED_EXCEPTION:
sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject);
break;
default:
sb.append("Unkown error at position ").append(position).append(".");
break;
}
return sb.toString();
}
}

View File

@ -1,672 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
/* The following code was generated by JFlex 1.4.2 */
package com.alibaba.nacos.client.logger.json.parser;
import com.alibaba.nacos.api.common.Constants;
import java.io.UnsupportedEncodingException;
/**
* Yylex
*
* @author Nacos
*/
class Yylex {
/**
* This character denotes the end of file
*/
public static final int YYEOF = -1;
/**
* initial size of the lookahead buffer
*/
private static final int ZZ_BUFFERSIZE = 16384;
/**
* lexical states
*/
public static final int YYINITIAL = 0;
public static final int STRING_BEGIN = 2;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l ZZ_LEXSTATE[l+1] is the state in the DFA for the
* lexical state l at the beginning of a line l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = {0, 0, 1, 1};
/**
* Translates characters to character classes
*/
private static final String ZZ_CMAP_PACKED =
"\11\0\1\7\1\7\2\0\1\7\22\0\1\7\1\0\1\11\10\0" + "\1\6\1\31\1\2\1\4\1\12\12\3\1\32\6\0\4\1\1\5"
+ "\1\1\24\0\1\27\1\10\1\30\3\0\1\22\1\13\2\1\1\21" + "\1\14\5\0\1\23\1\0\1\15\3\0\1\16\1\24\1\17\1\20"
+ "\5\0\1\25\1\0\1\26\uff82\0";
/**
* Translates characters to character classes
*/
private static final char[] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
/**
* Translates DFA states to action switch labels.
*/
private static final int[] ZZ_ACTION = zzUnpackAction();
private static final String ZZ_ACTION_PACKED_0 =
"\2\0\2\1\1\2\1\3\1\4\3\1\1\5\1\6" + "\1\7\1\10\1\11\1\12\1\13\1\14\1\15\5\0"
+ "\1\14\1\16\1\17\1\20\1\21\1\22\1\23\1\24" + "\1\0\1\25\1\0\1\25\4\0\1\26\1\27\2\0" + "\1\30";
private static int[] zzUnpackAction() {
int[] result = new int[45];
int offset = 0;
zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAction(String packed, int offset, int[] result) {
int i = 0;
int j = offset;
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do { result[j++] = value; } while (--count > 0);
}
return j;
}
/**
* Translates a state to a row index in the transition table
*/
private static final int[] ZZ_ROWMAP = zzUnpackRowMap();
private static final String ZZ_ROWMAP_PACKED_0 =
"\0\0\0\33\0\66\0\121\0\154\0\207\0\66\0\242" + "\0\275\0\330\0\66\0\66\0\66\0\66\0\66\0\66"
+ "\0\363\0\u010e\0\66\0\u0129\0\u0144\0\u015f\0\u017a\0\u0195" + "\0\66\0\66\0\66\0\66\0\66\0\66\0\66\0\66"
+ "\0\u01b0\0\u01cb\0\u01e6\0\u01e6\0\u0201\0\u021c\0\u0237\0\u0252" + "\0\66\0\66\0\u026d\0\u0288\0\66";
private static int[] zzUnpackRowMap() {
int[] result = new int[45];
int offset = 0;
zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
return result;
}
private static int zzUnpackRowMap(String packed, int offset, int[] result) {
int i = 0;
int j = offset;
int l = packed.length();
while (i < l) {
int high = packed.charAt(i++) << 16;
result[j++] = high | packed.charAt(i++);
}
return j;
}
/**
* The transition table of the DFA
*/
private static final int ZZ_TRANS[] = {2, 2, 3, 4, 2, 2, 2, 5, 2, 6, 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, 2, 10, 11, 12,
13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 18, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 19, 20, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 20, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 23, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 16, 16, 16, 16, 16, 16, 16, 16, -1,
-1, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, -1,
-1, -1, -1, -1, -1, -1, -1, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 33, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 34, 35,
-1, -1, 34, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 37, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 38, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 39, -1, 39, -1, 39, -1, -1, -1, -1,
-1, 39, 39, -1, -1, -1, -1, 39, 39, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 33, -1, 20, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 38, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 40, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 41, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 42, -1, 42, -1, 42, -1, -1, -1, -1, -1, 42, 42, -1, -1, -1, -1, 42, 42,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, -1, -1,
43, 43, -1, -1, -1, -1, 43, 43, -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, -1,
44, -1, 44, -1, -1, -1, -1, -1, 44, 44, -1, -1, -1, -1, 44, 44, -1, -1, -1,
-1, -1, -1, -1, -1,};
/**
* error codes
*/
private static final int ZZ_UNKNOWN_ERROR = 0;
private static final int ZZ_NO_MATCH = 1;
private static final int ZZ_PUSHBACK_2BIG = 2;
private static final int NIGTY = 90;
/**
* error messages for the codes above
*/
private static final String[] ZZ_ERROR_MSG = {"Unkown internal scanner error", "Error: could not match input",
"Error: pushback value was too large"};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
*/
private static final int[] ZZ_ATTRIBUTE = zzUnpackAttribute();
private static final String ZZ_ATTRIBUTE_PACKED_0 =
"\2\0\1\11\3\1\1\11\3\1\6\11\2\1\1\11" + "\5\0\10\11\1\0\1\1\1\0\1\1\4\0\2\11" + "\2\0\1\11";
private static int[] zzUnpackAttribute() {
int[] result = new int[45];
int offset = 0;
zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
return result;
}
private static int zzUnpackAttribute(String packed, int offset, int[] result) {
int i = 0;
int j = offset;
int l = packed.length();
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do { result[j++] = value; } while (--count > 0);
}
return j;
}
/**
* the input device
*/
private java.io.Reader zzReader;
/**
* the current state of the DFA
*/
private int zzState;
/**
* the current lexical state
*/
private int zzLexicalState = YYINITIAL;
/**
* this buffer contains the current text to be matched and is the source of the yytext() string
*/
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
/**
* the textposition at the last accepting state
*/
private int zzMarkedPos;
/**
* the current text position in the buffer
*/
private int zzCurrentPos;
/**
* startRead marks the beginning of the yytext() string in the buffer
*/
private int zzStartRead;
/**
* endRead marks the last character in the buffer, that has been read from input
*/
private int zzEndRead;
/**
* the number of characters up to the start of the matched text
*/
private int yychar;
/**
* zzAtEOF == true <=> the scanner is at the EOF
*/
private boolean zzAtEOF;
/**
* user code
*/
private StringBuffer sb = new StringBuffer();
int getPosition() {
return yychar;
}
/**
* Creates a new scanner There is also a java.io.InputStream version of this constructor.
*
* @param in the java.io.Reader to read input from.
*/
Yylex(java.io.Reader in) {
this.zzReader = in;
}
/**
* Creates a new scanner. There is also java.io.Reader version of this constructor.
*
* @param in the java.io.Inputstream to read input from.
* @throws UnsupportedEncodingException
*/
Yylex(java.io.InputStream in) throws UnsupportedEncodingException {
this(new java.io.InputStreamReader(in, Constants.ENCODE));
}
/**
* Unpacks the compressed character translation table.
*
* @param packed the packed character translation table
* @return the unpacked character translation table
*/
private static char[] zzUnpackCMap(String packed) {
char[] map = new char[0x10000];
int i = 0;
int j = 0;
while (i < NIGTY) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do { map[j++] = value; } while (--count > 0);
}
return map;
}
/**
* Refills the input buffer.
*
* @return <code>false</code>, iff there was new input.
* @throws java.io.IOException if any I/O-Error occurs
*/
private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead - zzStartRead);
/* translate stored positions */
zzEndRead -= zzStartRead;
zzCurrentPos -= zzStartRead;
zzMarkedPos -= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length) {
/* if not: blow it up */
char newBuffer[] = new char[zzCurrentPos * 2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
}
/* finally: fill the buffer with new input */
int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length - zzEndRead);
if (numRead > 0) {
zzEndRead += numRead;
return false;
}
// unlikely but not impossible: read 0 characters, but not at end of stream
if (numRead == 0) {
int c = zzReader.read();
if (c == -1) {
return true;
} else {
zzBuffer[zzEndRead++] = (char)c;
return false;
}
}
// numRead < 0
return true;
}
/**
* Closes the input stream.
*/
public final void yyclose() throws java.io.IOException {
zzAtEOF = true;
zzEndRead = zzStartRead;
if (zzReader != null) {
zzReader.close();
}
}
/**
* Resets the scanner to read from a new input stream. Does not close the old reader. All internal variables are
* reset, the old input stream <b>cannot</b> be reused (internal buffer is discarded and lost). Lexical state is set
* to <tt>ZZ_INITIAL</tt>.
*
* @param reader the new input stream
*/
public final void yyreset(java.io.Reader reader) {
zzReader = reader;
zzAtEOF = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
zzLexicalState = YYINITIAL;
}
/**
* Returns the current lexical state.
*/
public final int yystate() {
return zzLexicalState;
}
/**
* Enters a new lexical state
*
* @param newState the new lexical state
*/
public final void yybegin(int newState) {
zzLexicalState = newState;
}
/**
* Returns the text matched by the current regular expression.
*/
public final String yytext() {
return new String(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead);
}
/**
* Returns the character at position <tt>pos</tt> from the matched text. It is equivalent to yytext().charAt(pos),
* but faster
*
* @param pos the position of the character to fetch. A value from 0 to yylength()-1.
* @return the character at position pos
*/
public final char yycharat(int pos) {
return zzBuffer[zzStartRead + pos];
}
/**
* Returns the length of the matched text region.
*/
public final int yylength() {
return zzMarkedPos - zzStartRead;
}
/**
* Reports an error that occured while scanning. In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method will only be called with things that "Can't Possibly
* Happen". If this method is called, something is seriously wrong (e.g. a JFlex bug producing a faulty scanner
* etc.). Usual syntax/scanner level error handling should be done in error fallback rules.
*
* @param errorCode the code of the errormessage to display
*/
private void zzScanError(int errorCode) {
String message;
try {
message = ZZ_ERROR_MSG[errorCode];
} catch (ArrayIndexOutOfBoundsException e) {
message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
}
throw new Error(message);
}
/**
* Pushes the specified amount of characters back into the input stream. They will be read again by then next call
* of the scanning method
*
* @param number the number of characters to be read again. This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if (number > yylength()) {
zzScanError(ZZ_PUSHBACK_2BIG);
}
zzMarkedPos -= number;
}
/**
* Resumes scanning until the next regular expression is matched, the end of input is encountered or an I/O-Error
* occurs.
*
* @return the next token
* @throws java.io.IOException if any I/O-Error occurs
*/
@SuppressWarnings("PMD.SwitchStatementRule")
public Yytoken yylex() throws java.io.IOException, ParseException {
int zzInput;
int zzAction;
// cached fields:
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL = zzEndRead;
char[] zzBufferL = zzBuffer;
char[] zzCMapL = ZZ_CMAP;
int[] zzTransL = ZZ_TRANS;
int[] zzRowMapL = ZZ_ROWMAP;
int[] zzAttrL = ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL = zzMarkedPos;
yychar += zzMarkedPosL - zzStartRead;
zzAction = -1;
zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
zzState = ZZ_LEXSTATE[zzLexicalState];
zzForAction:
{
while (true) {
if (zzCurrentPosL < zzEndReadL) {
zzInput = zzBufferL[zzCurrentPosL++];
} else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
} else {
// store back cached positions
zzCurrentPos = zzCurrentPosL;
zzMarkedPos = zzMarkedPosL;
boolean eof = zzRefill();
// get translated positions and possibly new buffer
zzCurrentPosL = zzCurrentPos;
zzMarkedPosL = zzMarkedPos;
zzBufferL = zzBuffer;
zzEndReadL = zzEndRead;
if (eof) {
zzInput = YYEOF;
break zzForAction;
} else {
zzInput = zzBufferL[zzCurrentPosL++];
}
}
int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]];
if (zzNext == -1) {
break zzForAction;
}
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ((zzAttributes & 1) == 1) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ((zzAttributes & 8) == 8) {
break zzForAction;
}
}
}
}
// store back cached position
zzMarkedPos = zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 11: {
sb.append(yytext());
}
case 25:
break;
case 4: {
sb = null;
sb = new StringBuffer();
yybegin(STRING_BEGIN);
}
case 26:
break;
case 16: {
sb.append('\b');
}
case 27:
break;
case 6: {
return new Yytoken(Yytoken.TYPE_RIGHT_BRACE, null);
}
case 28:
break;
case 23: {
Boolean val = Boolean.valueOf(yytext());
return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 29:
break;
case 22: {
return new Yytoken(Yytoken.TYPE_VALUE, null);
}
case 30:
break;
case 13: {
yybegin(YYINITIAL);
return new Yytoken(Yytoken.TYPE_VALUE, sb.toString());
}
case 31:
break;
case 12: {
sb.append('\\');
}
case 32:
break;
case 21: {
Double val = Double.valueOf(yytext());
return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 33:
break;
case 1: {
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR,
Character.valueOf(yycharat(0)));
}
case 34:
break;
case 8: {
return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE, null);
}
case 35:
break;
case 19: {
sb.append('\r');
}
case 36:
break;
case 15: {
sb.append('/');
}
case 37:
break;
case 10: {
return new Yytoken(Yytoken.TYPE_COLON, null);
}
case 38:
break;
case 14: {
sb.append('"');
}
case 39:
break;
case 5: {
return new Yytoken(Yytoken.TYPE_LEFT_BRACE, null);
}
case 40:
break;
case 17: {
sb.append('\f');
}
case 41:
break;
case 24: {
try {
int ch = Integer.parseInt(yytext().substring(2), 16);
sb.append((char)ch);
} catch (Exception e) {
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e);
}
}
case 42:
break;
case 20: {
sb.append('\t');
}
case 43:
break;
case 7: {
return new Yytoken(Yytoken.TYPE_LEFT_SQUARE, null);
}
case 44:
break;
case 2: {
Long val = Long.valueOf(yytext());
return new Yytoken(Yytoken.TYPE_VALUE, val);
}
case 45:
break;
case 18: {
sb.append('\n');
}
case 46:
break;
case 9: {
return new Yytoken(Yytoken.TYPE_COMMA, null);
}
case 47:
break;
case 3: {
}
case 48:
break;
default:
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF = true;
return null;
} else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
}

View File

@ -1,81 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
/*
* $Id: Yytoken.java,v 1.1 2006/04/15 14:10:48 platform Exp $
* Created on 2006-4-15
*/
package com.alibaba.nacos.client.logger.json.parser;
/**
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
public class Yytoken {
/**
* JSON primitive value: string,number,boolean,null
*/
public static final int TYPE_VALUE = 0;
public static final int TYPE_LEFT_BRACE = 1;
public static final int TYPE_RIGHT_BRACE = 2;
public static final int TYPE_LEFT_SQUARE = 3;
public static final int TYPE_RIGHT_SQUARE = 4;
public static final int TYPE_COMMA = 5;
public static final int TYPE_COLON = 6;
/**
* end of file
*/
public static final int TYPE_EOF = -1;
public int type = 0;
public Object value = null;
public Yytoken(int type, Object value) {
this.type = type;
this.value = value;
}
public String toString() {
StringBuffer sb = new StringBuffer();
switch (type) {
case TYPE_VALUE:
sb.append("VALUE(").append(value).append(")");
break;
case TYPE_LEFT_BRACE:
sb.append("LEFT BRACE({)");
break;
case TYPE_RIGHT_BRACE:
sb.append("RIGHT BRACE(})");
break;
case TYPE_LEFT_SQUARE:
sb.append("LEFT SQUARE([)");
break;
case TYPE_RIGHT_SQUARE:
sb.append("RIGHT SQUARE(])");
break;
case TYPE_COMMA:
sb.append("COMMA(,)");
break;
case TYPE_COLON:
sb.append("COLON(:)");
break;
case TYPE_EOF:
sb.append("END OF FILE");
break;
default:
break;
}
return sb.toString();
}
}

View File

@ -1,143 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.log4j2;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.option.Log4j2ActivateOption;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.logger.support.LoggerSupport;
import com.alibaba.nacos.client.logger.util.MessageUtil;
/**
* Log4j2Logger
*
* @author Nacos
*/
public class Log4j2Logger extends LoggerSupport implements Logger {
private org.apache.logging.log4j.Logger delegate;
public Log4j2Logger(org.apache.logging.log4j.Logger delegate) {
super(delegate);
if (delegate == null) {
throw new IllegalArgumentException("delegate Logger is null");
}
this.delegate = delegate;
this.activateOption = new Log4j2ActivateOption(delegate);
}
@Override
public void debug(String context, String message) {
if (isDebugEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.debug(MessageUtil.getMessage(context, message));
}
}
@Override
public void debug(String context, String format, Object... args) {
if (isDebugEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.debug(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void info(String context, String message) {
if (isInfoEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.info(MessageUtil.getMessage(context, message));
}
}
@Override
public void info(String context, String format, Object... args) {
if (isInfoEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.info(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void warn(String message, Throwable t) {
if (isWarnEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.warn(MessageUtil.getMessage(null, message), t);
}
}
@Override
public void warn(String context, String message) {
if (isWarnEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.warn(MessageUtil.getMessage(context, message));
}
}
@Override
public void warn(String context, String format, Object... args) {
if (isWarnEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.warn(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void error(String context, String errorCode, String message) {
if (isErrorEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.error(MessageUtil.getMessage(context, errorCode, message));
}
}
@Override
public void error(String context, String errorCode, String message, Throwable t) {
if (isErrorEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.error(MessageUtil.getMessage(context, errorCode, message), t);
}
}
@Override
public void error(String context, String errorCode, String format, Object... args) {
if (isErrorEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.error(MessageUtil.getMessage(context, errorCode, MessageUtil.formatMessage(format, args)));
}
}
@Override
public boolean isDebugEnabled() {
return delegate.isDebugEnabled();
}
@Override
public boolean isInfoEnabled() {
return delegate.isInfoEnabled();
}
@Override
public boolean isWarnEnabled() {
return delegate.isWarnEnabled();
}
@Override
public boolean isErrorEnabled() {
return delegate.isErrorEnabled();
}
}

View File

@ -1,55 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.log4j2;
import org.apache.logging.log4j.LogManager;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.nop.NopLogger;
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
import com.alibaba.nacos.client.logger.support.LogLog;
/**
* Log4j2Logger Factory
*
* @author Nacos
*/
public class Log4j2LoggerFactory implements ILoggerFactory {
public Log4j2LoggerFactory() throws ClassNotFoundException {
Class.forName("org.apache.logging.log4j.core.Logger");
}
@Override
public Logger getLogger(Class<?> clazz) {
try {
return new Log4j2Logger(LogManager.getLogger(clazz));
} catch (Throwable t) {
LogLog.error("Failed to get Log4j2Logger", t);
return new NopLogger();
}
}
@Override
public Logger getLogger(String name) {
try {
return new Log4j2Logger(LogManager.getLogger(name));
} catch (Throwable t) {
LogLog.error("Failed to get Log4j2Logger", t);
return new NopLogger();
}
}
}

View File

@ -1,100 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.nop;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.LoggerSupport;
/**
* NopLogger
*
* @author Nacos
*/
public class NopLogger extends LoggerSupport implements Logger {
public NopLogger() {
super(null);
}
@Override
public void debug(String context, String message) {
}
@Override
public void debug(String context, String format, Object... args) {
}
@Override
public void info(String context, String message) {
}
@Override
public void info(String context, String format, Object... args) {
}
public void warn(String message, Throwable t) {
}
@Override
public void warn(String context, String message) {
}
@Override
public void warn(String context, String format, Object... args) {
}
@Override
public void error(String context, String errorCode, String message) {
}
@Override
public void error(String context, String errorCode, String message, Throwable t) {
}
@Override
public void error(String context, String errorCode, String format, Object... args) {
}
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public boolean isInfoEnabled() {
return false;
}
@Override
public boolean isWarnEnabled() {
return false;
}
@Override
public boolean isErrorEnabled() {
return false;
}
}

View File

@ -1,37 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.nop;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
/**
* NopLogger Factory
*
* @author Nacos
*/
public class NopLoggerFactory implements ILoggerFactory {
@Override
public Logger getLogger(Class<?> clazz) {
return new NopLogger();
}
@Override
public Logger getLogger(String name) {
return new NopLogger();
}
}

View File

@ -1,71 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.option;
import com.alibaba.nacos.client.logger.Level;
import com.alibaba.nacos.client.logger.support.LogLog;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
/**
* AbstractActiveOption
*
* @author Nacos
*/
public abstract class AbstractActiveOption implements ActivateOption {
protected String productName;
protected Level level;
@Override
public String getProductName() {
return productName;
}
@Override
public Level getLevel() {
return level;
}
protected void setProductName(String productName) {
if (this.productName == null && productName != null) {
this.productName = productName;
}
}
public static void invokeMethod(Object object, List<Object[]> args) {
if (args != null && object != null) {
for (Object[] arg : args) {
if (arg != null && arg.length == 3) {
try {
Method m = object.getClass().getMethod((String)arg[0], (Class<?>[])arg[1]);
m.invoke(object, arg[2]);
} catch (NoSuchMethodException e) {
LogLog.info("Can't find method for " + object.getClass() + " " + arg[0] + " " + arg[2]);
} catch (IllegalAccessException e) {
LogLog.info("Can't invoke method for " + object.getClass() + " " + arg[0] + " " + arg[2]);
} catch (InvocationTargetException e) {
LogLog.info("Can't invoke method for " + object.getClass() + " " + arg[0] + " " + arg[2]);
} catch (Throwable t) {
LogLog.info("Can't invoke method for " + object.getClass() + " " + arg[0] + " " + arg[2]);
}
}
}
}
}
}

View File

@ -1,195 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.option;
import java.util.List;
import java.util.Map;
import com.alibaba.nacos.client.logger.Level;
import com.alibaba.nacos.client.logger.Logger;
/**
* <pre>
* 激活Logger的选项包括
* Appender/Layout
* Level
* Additivity
* Aysnc
* 请参考具体的实现逻辑
* </pre>
*
* @author zhuyong 2014年3月20日 上午10:20:51
*/
public interface ActivateOption {
/**
* 设置ConsoleAppender生产环境慎用
*
* @param target System.out or System.err
* @param encoding 编码
*/
void activateConsoleAppender(String target, String encoding);
/**
* 设置FileAppender日志按天回滚
*
* @param productName 中间件产品名如hsf, tddl
* @param file 日志文件名如hsf.log支持子目录如client/hsf.log
* @param encoding 编码
*/
void activateAppender(String productName, String file, String encoding);
/**
* 设置AsyncAppender内嵌DailyRollingFileAppender日志按天回滚参考 {@link ActivateOption#activateAsync(int, int)}
*
* @param productName 中间件产品名如hsf, tddl
* @param file 日志文件名如hsf.log支持子目录如client/hsf.log
* @param encoding 编码
*/
@Deprecated
void activateAsyncAppender(String productName, String file, String encoding);
/**
* 设置AsyncAppender内嵌DailyRollingFileAppender日志按天回滚参考 {@link ActivateOption#activateAsync(int, int)}
*
* @param productName 中间件产品名如hsf, tddl
* @param file 日志文件名如hsf.log支持子目录如client/hsf.log
* @param encoding 编码
* @param queueSize 等待队列大小
* @param discardingThreshold discardingThreshold该参数仅对logback实现有效log4j和log4j2无效
*/
@Deprecated
void activateAsyncAppender(String productName, String file, String encoding, int queueSize,
int discardingThreshold);
/**
* 设置按天和文件大小回滚
*
* @param productName 中间件产品名如hsf, tddl
* @param file 日志文件名如hsf.log支持子目录如client/hsf.log
* @param encoding 编码
* @param size 文件大小如300MB支持KBMBGB该参数对log4j实现不生效log4j2和logback有效
*/
void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size);
/**
* <pre>
* 设置按日期格式和文件大小回滚
* 说明Log4j 对日期格式不生效只有按大小回滚同时不支持备份文件即达到文件大小直接截断如果需要备份文件请参考带 maxBackupIndex 参数的方法
* </pre>
*
* @param productName 中间件产品名如hsf, tddl
* @param file 日志文件名如hsf.log支持子目录如client/hsf.log
* @param encoding 编码
* @param size 文件大小如300MB支持KBMBGB
* @param datePattern 日期格式如yyyy-MM-dd yyyy-MM请自行保证格式正确该参数对log4j实现不生效log4j2和logback有效
*/
void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern);
/**
* <pre>
* 设置按日期格式文件大小最大备份文件数回滚
* 说明
* 1Log4j 对日期格式不生效只有按大小备份文件数回滚备份文件数 maxBackupIndex 参数必须是 >= 0 的整数为0时表示直接截断不备份
* 2备份日志格式说明
* Log4jnotify.log.1, notify.log.2即备份文件以 .1 .2结尾序号从1开始
* Logback: notify.log.2014-09-19.0 notify.log.2014-09-19.1即中间会带日期格式同时序号从0开始
* </pre>
*
* @param productName 中间件产品名如hsf, tddl
* @param file 日志文件名如hsf.log支持子目录如client/hsf.log
* @param encoding 编码
* @param size 文件大小如300MB支持KBMBGB
* @param datePattern 日期格式如yyyy-MM-dd yyyy-MM请自行保证格式正确该参数对log4j实现不生效log4j2和logback有效
* @param maxBackupIndex 最大备份文件数如10对于 Logback则是保留10天的文件但是这10天内的文件则会按大小回滚
*/
void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern, int maxBackupIndex);
/**
* <pre>
* 设置按文件大小最大备份文件数回滚
* 说明
* 1Log4j 备份文件数 maxBackupIndex 参数必须是 >= 0 的整数为0时表示直接截断不备份
* 2备份日志格式说明
* Log4jnotify.log.1, notify.log.2即备份文件以 .1 .2结尾序号从1开始
* Logback: notify.log.1 notify.log.1
* </pre>
*
* @param productName 中间件产品名如hsf, tddl
* @param file 日志文件名如hsf.log支持子目录如client/hsf.log
* @param encoding 编码
* @param size 文件大小如300MB支持KBMBGB
* @param maxBackupIndex 最大备份文件数如10
*/
void activateAppenderWithSizeRolling(String productName, String file, String encoding, String size,
int maxBackupIndex);
/**
* 将当前logger对象的appender设置为异步Appender 注意此logger需要提前进行Appender的初始化
*
* @param queueSize 等待队列大小
* @param discardingThreshold discardingThreshold该参数仅对logback实现有效log4j和log4j2无效
* @since 0.2.2
*/
void activateAsync(int queueSize, int discardingThreshold);
/**
* 将当前logger对象的appender设置为异步Appender 注意此logger需要提前进行Appender的初始化
*
* @param args AsyncAppender配置参数请自行保证参数的正确性要求每个Object[]有3个元素第一个为set方法名第二个为方法类型数组第三个为对应的参数值 args.add(new
* Object[] { "setBufferSize", new Class<?>[] { int.class }, queueSize });
* @since 0.2.3
*/
void activateAsync(List<Object[]> args);
/**
* 使用logger对象的appender来初始化当前logger
*
* @param logger
*/
void activateAppender(Logger logger);
/**
* 设置日志级别
*
* @param level 日志级别
* @see Level
*/
void setLevel(Level level);
/**
* 获取日志级别
*
* @return level
*/
Level getLevel();
/**
* 设置日志是否Attach到Parent
*
* @param additivity true or false
*/
void setAdditivity(boolean additivity);
/**
* 获取所属的产品名
*
* @return 所属的产品名
*/
String getProductName();
}

View File

@ -1,285 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.option;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.AsyncAppender;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.appender.rolling.*;
import org.apache.logging.log4j.core.async.ArrayBlockingQueueFactory;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import com.alibaba.nacos.client.logger.Level;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
/**
* @author zhuyong on 2017/4/13.
*/
public class Log4j2ActivateOption extends AbstractActiveOption {
protected org.apache.logging.log4j.core.Logger logger;
protected Configuration configuration;
public Log4j2ActivateOption(org.apache.logging.log4j.Logger logger) {
if (logger != null) {
if (logger instanceof org.apache.logging.log4j.core.Logger) {
this.logger = (org.apache.logging.log4j.core.Logger)logger;
configuration = this.logger.getContext().getConfiguration();
} else {
throw new RuntimeException(
"logger must instanceof org.apache.logging.log4j.core.Logger, " + logger.getClass().getName());
}
}
}
@Override
public void activateConsoleAppender(String target, String encoding) {
org.apache.logging.log4j.core.Layout layout = org.apache.logging.log4j.core.layout.PatternLayout.newBuilder().
withConfiguration(configuration)
.withPattern(LoggerHelper.getPattern())
.withCharset(Charset.forName(encoding))
.build();
org.apache.logging.log4j.core.appender.ConsoleAppender appender = ConsoleAppender.createAppender(layout, null,
ConsoleAppender.Target.valueOf(target.toUpperCase().replace(".", "_")), "LoggerApiConsoleAppender", false,
false, true);
appender.start();
removeAllAppenders(logger);
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAppender(String productName, String file, String encoding) {
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
.withFileName(LoggerHelper.getLogFileP(productName, file))
.withAppend(true)
.withBufferedIo(true)
.setConfiguration(configuration)
.withFilePattern(LoggerHelper.getLogFile(productName, file) + ".%d{yyyy-MM-dd}")
.withLayout(buildLayout(encoding))
.withCreateOnDemand(false)
.withPolicy(TimeBasedTriggeringPolicy.createPolicy("1", "true"))
.withStrategy(DefaultRolloverStrategy.createStrategy(null, null, "nomax", null, null, false, configuration))
.build();
appender.start();
removeAllAppenders(logger);
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAsyncAppender(String productName, String file, String encoding) {
activateAsyncAppender(productName, file, encoding, Integer.MIN_VALUE, Integer.MIN_VALUE);
}
@Override
public void activateAsyncAppender(String productName, String file, String encoding, int queueSize,
int discardingThreshold) {
activateAppender(productName, file, encoding);
activateAsync(queueSize, discardingThreshold);
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size) {
activateAppenderWithTimeAndSizeRolling(productName, file, encoding, size, "yyyy-MM-dd");
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern) {
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
.withFileName(LoggerHelper.getLogFileP(productName, file))
.withAppend(true)
.withBufferedIo(true)
.setConfiguration(configuration)
.withFilePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}")
.withLayout(buildLayout(encoding))
.withCreateOnDemand(false)
.withPolicy(CompositeTriggeringPolicy.createPolicy(TimeBasedTriggeringPolicy.createPolicy("1", "true"),
SizeBasedTriggeringPolicy.createPolicy(size)))
.withStrategy(DefaultRolloverStrategy.createStrategy(null, null, "nomax", null, null, false, configuration))
.build();
appender.start();
removeAllAppenders(logger);
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern, int maxBackupIndex) {
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
.withFileName(LoggerHelper.getLogFileP(productName, file))
.withAppend(true)
.withBufferedIo(true)
.setConfiguration(configuration)
.withFilePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}.%i")
.withLayout(buildLayout(encoding))
.withCreateOnDemand(false)
.withPolicy(CompositeTriggeringPolicy.createPolicy(TimeBasedTriggeringPolicy.createPolicy("1", "true"),
SizeBasedTriggeringPolicy.createPolicy(size)))
.withStrategy(DefaultRolloverStrategy
.createStrategy(String.valueOf(maxBackupIndex), "1", "max", null, null, false, configuration))
.build();
appender.start();
removeAllAppenders(logger);
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAppenderWithSizeRolling(String productName, String file, String encoding, String size,
int maxBackupIndex) {
org.apache.logging.log4j.core.appender.RollingFileAppender appender = RollingFileAppender.newBuilder()
.withName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender")
.withFileName(LoggerHelper.getLogFileP(productName, file))
.withAppend(true)
.withBufferedIo(true)
.setConfiguration(configuration)
.withFilePattern(LoggerHelper.getLogFile(productName, file) + ".%i")
.withLayout(buildLayout(encoding))
.withCreateOnDemand(false)
.withPolicy(SizeBasedTriggeringPolicy.createPolicy(size))
.withStrategy(DefaultRolloverStrategy
.createStrategy(String.valueOf(maxBackupIndex), "1", "max", null, null, false, configuration))
.build();
appender.start();
removeAllAppenders(logger);
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAsync(int queueSize, int discardingThreshold) {
List<Object[]> args = new ArrayList<Object[]>();
if (queueSize != Integer.MIN_VALUE) {
args.add(new Object[] {"setBufferSize", new Class<?>[] {int.class}, queueSize});
}
activateAsync(args);
}
@Override
public void activateAsync(List<Object[]> args) {
Map<String, Appender> appenders = logger.getAppenders();
if (appenders == null) {
throw new IllegalStateException("Activate async appender failed, no appender exist.");
}
AppenderRef[] refs = new AppenderRef[appenders.size()];
int i = 0;
for (Appender appender : appenders.values()) {
configuration.addAppender(appender);
refs[i++] = AppenderRef.createAppenderRef(appender.getName(), null, null);
}
AsyncAppender.Builder builder = AsyncAppender.newBuilder()
.setName(productName + "." + logger.getName() + ".AsyncAppender")
.setConfiguration(configuration)
.setAppenderRefs(refs)
.setBlockingQueueFactory(ArrayBlockingQueueFactory.<LogEvent>createFactory());
invokeMethod(builder, args);
AsyncAppender asyncAppender = builder.build();
asyncAppender.start();
removeAllAppenders(logger);
logger.addAppender(asyncAppender);
setProductName(productName);
}
@Override
public void activateAppender(Logger logger) {
if (!(logger.getDelegate() instanceof org.apache.logging.log4j.core.Logger)) {
throw new IllegalArgumentException("logger must be org.apache.logging.log4j.core.Logger, but it's "
+ logger.getDelegate().getClass());
}
activateAppender(((org.apache.logging.log4j.core.Logger)logger.getDelegate()));
setProductName(logger.getProductName());
}
protected void activateAppender(org.apache.logging.log4j.core.Logger logger) {
removeAllAppenders(this.logger);
Map<String, Appender> appenders = null;
if ((appenders = logger.getAppenders()) != null) {
for (Appender appender : appenders.values()) {
this.logger.addAppender(appender);
}
}
}
@Override
public void setLevel(Level level) {
this.level = level;
org.apache.logging.log4j.Level l = org.apache.logging.log4j.Level.toLevel(level.getName(),
org.apache.logging.log4j.Level.ERROR);
logger.setLevel(l);
logger.getContext().getConfiguration().getLoggerConfig(this.logger.getName()).setLevel(l);
}
@Override
public void setAdditivity(boolean additivity) {
logger.setAdditive(additivity);
}
protected org.apache.logging.log4j.core.Layout buildLayout(String encoding) {
org.apache.logging.log4j.core.Layout layout = org.apache.logging.log4j.core.layout.PatternLayout.newBuilder().
withConfiguration(configuration)
.withPattern(LoggerHelper.getPattern())
.withCharset(Charset.forName(encoding))
.build();
return layout;
}
protected void removeAllAppenders(org.apache.logging.log4j.core.Logger logger) {
Map<String, Appender> appenders = logger.getAppenders();
if (appenders != null) {
for (Appender appender : appenders.values()) {
logger.removeAppender(appender);
}
}
}
}

View File

@ -1,335 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.option;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.rolling.*;
import ch.qos.logback.core.util.FileSize;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.alibaba.nacos.client.logger.Level;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.LogLog;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
/**
* logback 0.9.18版本及以前适用
*
* @author zhuyong 2014年3月20日 上午11:16:26
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class Logback918ActivateOption extends AbstractActiveOption {
private ch.qos.logback.classic.Logger logger;
public Logback918ActivateOption(Object logger) {
if (logger instanceof ch.qos.logback.classic.Logger) {
this.logger = (ch.qos.logback.classic.Logger)logger;
} else {
throw new IllegalArgumentException("logger must be instanceof ch.qos.logback.classic.Logger");
}
}
@Override
public void activateConsoleAppender(String target, String encoding) {
ch.qos.logback.core.ConsoleAppender appender = new ch.qos.logback.core.ConsoleAppender();
appender.setContext(LogbackLoggerContextUtil.getLoggerContext());
appender.setTarget(target);
PatternLayout layout = new PatternLayout();
layout.setPattern(LoggerHelper.getPattern());
layout.setContext(LogbackLoggerContextUtil.getLoggerContext());
layout.start();
appender.setLayout(layout);
appender.start();
logger.detachAndStopAllAppenders();
logger.addAppender(appender);
}
@Override
public void activateAppender(String productName, String file, String encoding) {
ch.qos.logback.core.Appender appender = getLogbackDailyRollingFileAppender(productName, file, encoding);
logger.detachAndStopAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAsyncAppender(String productName, String file, String encoding) {
activateAsyncAppender(productName, file, encoding, Integer.MIN_VALUE, Integer.MIN_VALUE);
}
public void activateAsyncAppender(String productName, String file, String encoding, int queueSize,
int discardingThreshold) {
activateAppender(productName, file, encoding);
activateAsync(queueSize, discardingThreshold);
}
@Override
public void setLevel(Level level) {
this.level = level;
logger.setLevel(ch.qos.logback.classic.Level.valueOf(level.getName()));
}
@Override
public void setAdditivity(boolean additivity) {
logger.setAdditive(additivity);
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size) {
ch.qos.logback.core.Appender appender = getLogbackDailyAndSizeRollingFileAppender(productName, file, encoding,
size);
logger.detachAndStopAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
protected ch.qos.logback.core.Appender getLogbackDailyRollingFileAppender(String productName, String file,
String encoding) {
RollingFileAppender appender = new RollingFileAppender();
appender.setContext(LogbackLoggerContextUtil.getLoggerContext());
appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
appender.setAppend(true);
appender.setFile(LoggerHelper.getLogFile(productName, file));
TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
rolling.setParent(appender);
rolling.setFileNamePattern(LoggerHelper.getLogFile(productName, file) + ".%d{yyyy-MM-dd}");
rolling.setContext(LogbackLoggerContextUtil.getLoggerContext());
rolling.start();
appender.setRollingPolicy(rolling);
PatternLayout layout = new PatternLayout();
layout.setPattern(LoggerHelper.getPattern(productName));
layout.setContext(LogbackLoggerContextUtil.getLoggerContext());
layout.start();
appender.setLayout(layout);
// 启动
appender.start();
return appender;
}
protected ch.qos.logback.core.Appender getLogbackDailyAndSizeRollingFileAppender(String productName, String file,
String encoding, String size) {
return getLogbackDailyAndSizeRollingFileAppender(productName, file, encoding, size, "yyyy-MM-dd", -1);
}
@Override
public void activateAppender(Logger logger) {
if (!(logger.getDelegate() instanceof ch.qos.logback.classic.Logger)) {
throw new IllegalArgumentException(
"logger must be ch.qos.logback.classic.Logger, but it's " + logger.getDelegate().getClass());
}
this.logger.detachAndStopAllAppenders();
Iterator<ch.qos.logback.core.Appender<ILoggingEvent>> iter = ((ch.qos.logback.classic.Logger)logger
.getDelegate()).iteratorForAppenders();
while (iter.hasNext()) {
ch.qos.logback.core.Appender<ILoggingEvent> appender = iter.next();
this.logger.addAppender(appender);
}
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern) {
ch.qos.logback.core.Appender appender = getLogbackDailyAndSizeRollingFileAppender(productName, file, encoding,
size, datePattern, -1);
logger.detachAndStopAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
protected ch.qos.logback.core.Appender getLogbackDailyAndSizeRollingFileAppender(String productName, String file,
String encoding, String size,
String datePattern,
int maxBackupIndex) {
RollingFileAppender appender = new RollingFileAppender();
appender.setContext(LogbackLoggerContextUtil.getLoggerContext());
appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
appender.setAppend(true);
appender.setFile(LoggerHelper.getLogFile(productName, file));
TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
rolling.setParent(appender);
if (maxBackupIndex >= 0) {
rolling.setMaxHistory(maxBackupIndex);
}
rolling.setFileNamePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}.%i");
rolling.setContext(LogbackLoggerContextUtil.getLoggerContext());
SizeAndTimeBasedFNATP fnatp = new SizeAndTimeBasedFNATP();
setMaxFileSize(fnatp, size);
fnatp.setTimeBasedRollingPolicy(rolling);
rolling.setTimeBasedFileNamingAndTriggeringPolicy(fnatp);
rolling.start();
appender.setRollingPolicy(rolling);
PatternLayout layout = new PatternLayout();
layout.setPattern(LoggerHelper.getPattern(productName));
layout.setContext(LogbackLoggerContextUtil.getLoggerContext());
layout.start();
appender.setLayout(layout);
// 启动
appender.start();
return appender;
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern, int maxBackupIndex) {
ch.qos.logback.core.Appender appender = getLogbackDailyAndSizeRollingFileAppender(productName, file, encoding,
size, datePattern,
maxBackupIndex);
logger.detachAndStopAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAppenderWithSizeRolling(String productName, String file, String encoding, String size,
int maxBackupIndex) {
ch.qos.logback.core.Appender appender = getSizeRollingAppender(productName, file, encoding, size,
maxBackupIndex);
logger.detachAndStopAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAsync(int queueSize, int discardingThreshold) {
List<Object[]> args = new ArrayList<Object[]>();
if (queueSize != Integer.MIN_VALUE) {
args.add(new Object[] {"setQueueSize", new Class<?>[] {int.class}, queueSize});
}
if (discardingThreshold != Integer.MIN_VALUE) {
args.add(new Object[] {"setDiscardingThreshold", new Class<?>[] {int.class}, discardingThreshold});
}
activateAsync(args);
}
@Override
public void activateAsync(List<Object[]> args) {
AsyncAppender asynAppender = new AsyncAppender();
invokeMethod(asynAppender, args);
asynAppender.setName(productName + "." + logger.getName() + ".AsyncAppender");
asynAppender.setContext(LogbackLoggerContextUtil.getLoggerContext());
Iterator<Appender<ILoggingEvent>> iterator = logger.iteratorForAppenders();
boolean hasAppender = false;
while (iterator.hasNext()) {
hasAppender = true;
asynAppender.addAppender(iterator.next());
}
if (!hasAppender) {
throw new IllegalStateException("Activate async appender failed, no appender exist.");
}
asynAppender.start();
iterator = logger.iteratorForAppenders();
while (iterator.hasNext()) {
logger.detachAppender(iterator.next());
}
logger.addAppender(asynAppender);
setProductName(productName);
}
protected ch.qos.logback.core.Appender getSizeRollingAppender(String productName, String file, String encoding,
String size, int maxBackupIndex) {
RollingFileAppender appender = new RollingFileAppender();
appender.setContext(LogbackLoggerContextUtil.getLoggerContext());
appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
appender.setAppend(true);
appender.setFile(LoggerHelper.getLogFile(productName, file));
SizeBasedTriggeringPolicy triggerPolicy = new SizeBasedTriggeringPolicy();
setMaxFileSize(triggerPolicy, size);
triggerPolicy.setContext(LogbackLoggerContextUtil.getLoggerContext());
triggerPolicy.start();
FixedWindowRollingPolicy rolling = new FixedWindowRollingPolicy();
rolling.setContext(LogbackLoggerContextUtil.getLoggerContext());
rolling.setParent(appender);
rolling.setFileNamePattern(LoggerHelper.getLogFile(productName, file) + ".%i");
rolling.setParent(appender);
if (maxBackupIndex >= 0) {
rolling.setMaxIndex(maxBackupIndex);
}
rolling.start();
appender.setRollingPolicy(rolling);
appender.setTriggeringPolicy(triggerPolicy);
PatternLayout layout = new PatternLayout();
layout.setPattern(LoggerHelper.getPattern(productName));
layout.setContext(LogbackLoggerContextUtil.getLoggerContext());
layout.start();
appender.setLayout(layout);
// 启动
appender.start();
return appender;
}
/**
* logback 1.1.8开始不再支持setMaxFileSize(String)方法
*/
protected void setMaxFileSize(Object policy, String size) {
try {
try {
Method setMaxFileSizeMethod = policy.getClass().getDeclaredMethod("setMaxFileSize", String.class);
setMaxFileSizeMethod.invoke(policy, size);
} catch (NoSuchMethodException e) {
Method setMaxFileSizeMethod = policy.getClass().getDeclaredMethod("setMaxFileSize", FileSize.class);
setMaxFileSizeMethod.invoke(policy, FileSize.valueOf(size));
}
} catch (Throwable t) {
throw new RuntimeException("Failed to setMaxFileSize", t);
}
}
}

View File

@ -1,154 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.option;
import java.io.File;
import java.nio.charset.Charset;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
/**
* ActivateOption的Logback 0.9.19及后续版本的实现
*
* @author zhuyong 2014年3月20日 上午10:24:58
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class LogbackActivateOption extends Logback918ActivateOption {
public LogbackActivateOption(Object logger) {
super(logger);
}
protected ch.qos.logback.core.Appender getLogbackDailyRollingFileAppender(String productName, String file,
String encoding) {
RollingFileAppender appender = new RollingFileAppender();
appender.setContext(LogbackLoggerContextUtil.getLoggerContext());
appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
appender.setAppend(true);
appender.setFile(LoggerHelper.getLogFile(productName, file));
TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
rolling.setParent(appender);
rolling.setFileNamePattern(LoggerHelper.getLogFile(productName, file) + ".%d{yyyy-MM-dd}");
rolling.setContext(LogbackLoggerContextUtil.getLoggerContext());
rolling.start();
appender.setRollingPolicy(rolling);
PatternLayoutEncoder layout = new PatternLayoutEncoder();
layout.setPattern(LoggerHelper.getPattern(productName));
layout.setCharset(Charset.forName(encoding));
appender.setEncoder(layout);
layout.setContext(LogbackLoggerContextUtil.getLoggerContext());
layout.start();
// 启动
appender.start();
return appender;
}
protected ch.qos.logback.core.Appender getLogbackDailyAndSizeRollingFileAppender(String productName, String file,
String encoding, String size) {
return getLogbackDailyAndSizeRollingFileAppender(productName, file, encoding, size, "yyyy-MM-dd", -1);
}
protected ch.qos.logback.core.Appender getLogbackDailyAndSizeRollingFileAppender(String productName, String file,
String encoding, String size,
String datePattern,
int maxBackupIndex) {
RollingFileAppender appender = new RollingFileAppender();
appender.setContext(LogbackLoggerContextUtil.getLoggerContext());
appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
appender.setAppend(true);
appender.setFile(LoggerHelper.getLogFile(productName, file));
TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
rolling.setParent(appender);
if (maxBackupIndex >= 0) {
rolling.setMaxHistory(maxBackupIndex);
}
rolling.setFileNamePattern(LoggerHelper.getLogFile(productName, file) + ".%d{" + datePattern + "}.%i");
rolling.setContext(LogbackLoggerContextUtil.getLoggerContext());
SizeAndTimeBasedFNATP fnatp = new SizeAndTimeBasedFNATP();
setMaxFileSize(fnatp, size);
fnatp.setTimeBasedRollingPolicy(rolling);
rolling.setTimeBasedFileNamingAndTriggeringPolicy(fnatp);
rolling.start();
appender.setRollingPolicy(rolling);
PatternLayoutEncoder layout = new PatternLayoutEncoder();
layout.setPattern(LoggerHelper.getPattern(productName));
layout.setCharset(Charset.forName(encoding));
appender.setEncoder(layout);
layout.setContext(LogbackLoggerContextUtil.getLoggerContext());
layout.start();
// 启动
appender.start();
return appender;
}
protected ch.qos.logback.core.Appender getSizeRollingAppender(String productName, String file, String encoding,
String size, int maxBackupIndex) {
RollingFileAppender appender = new RollingFileAppender();
appender.setContext(LogbackLoggerContextUtil.getLoggerContext());
appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
appender.setAppend(true);
appender.setFile(LoggerHelper.getLogFile(productName, file));
SizeBasedTriggeringPolicy triggerPolicy = new SizeBasedTriggeringPolicy();
setMaxFileSize(triggerPolicy, size);
triggerPolicy.setContext(LogbackLoggerContextUtil.getLoggerContext());
triggerPolicy.start();
FixedWindowRollingPolicy rolling = new FixedWindowRollingPolicy();
rolling.setContext(LogbackLoggerContextUtil.getLoggerContext());
rolling.setParent(appender);
rolling.setFileNamePattern(LoggerHelper.getLogFile(productName, file) + ".%i");
rolling.setParent(appender);
if (maxBackupIndex >= 0) {
rolling.setMaxIndex(maxBackupIndex);
}
rolling.start();
appender.setRollingPolicy(rolling);
appender.setTriggeringPolicy(triggerPolicy);
PatternLayoutEncoder layout = new PatternLayoutEncoder();
layout.setPattern(LoggerHelper.getPattern(productName));
layout.setCharset(Charset.forName(encoding));
appender.setEncoder(layout);
layout.setContext(LogbackLoggerContextUtil.getLoggerContext());
layout.start();
// 启动
appender.start();
return appender;
}
}

View File

@ -1,48 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.option;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.LogbackException;
/**
* Logback Context Util
*
* @author Nacos
*/
public class LogbackLoggerContextUtil {
private static LoggerContext loggerContext = null;
public static LoggerContext getLoggerContext() {
if (loggerContext == null) {
ILoggerFactory lcObject = LoggerFactory.getILoggerFactory();
if (!(lcObject instanceof LoggerContext)) {
throw new LogbackException(
"Expected LOGBACK binding with SLF4J, but another log system has taken the place: "
+ lcObject.getClass().getSimpleName());
}
loggerContext = (LoggerContext)lcObject;
}
return loggerContext;
}
}

View File

@ -1,70 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.option;
import java.lang.reflect.Field;
import com.alibaba.nacos.client.logger.Logger;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* @author zhuyong on 2017/4/18.
*/
public class Slf4jLog4j2AdapterActivateOption extends Log4j2ActivateOption {
private static Field loggerField = null;
static {
try {
loggerField = org.apache.logging.slf4j.Log4jLogger.class.getDeclaredField("logger");
loggerField.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException("logger must be instanceof org.apache.logging.slf4j.Log4jLogger", e);
}
}
public Slf4jLog4j2AdapterActivateOption(Object logger) {
super(null);
try {
org.apache.logging.log4j.core.Logger log4j2Logger = (org.apache.logging.log4j.core.Logger)loggerField.get(
logger);
super.logger = log4j2Logger;
super.configuration = super.logger.getContext().getConfiguration();
} catch (Exception e) {
throw new RuntimeException("logger must be instanceof org.apache.logging.slf4j.Log4jLogger", e);
}
}
@Override
@SuppressFBWarnings("NM_WRONG_PACKAGE")
public void activateAppender(Logger logger) {
if (!(logger.getDelegate() instanceof org.apache.logging.slf4j.Log4jLogger)) {
throw new IllegalArgumentException(
"logger must be org.apache.logging.slf4j.Log4jLogger, but it's "
+ logger.getDelegate().getClass());
}
try {
org.apache.logging.log4j.core.Logger log4j2Logger = (org.apache.logging.log4j.core.Logger)loggerField.get(
logger.getDelegate());
super.activateAppender(log4j2Logger);
} catch (Exception e) {
throw new RuntimeException("activateAppender error, ", e);
}
}
}

View File

@ -1,180 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.slf4j;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.option.ActivateOption;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.logger.support.LoggerSupport;
import com.alibaba.nacos.client.logger.util.MessageUtil;
import java.lang.reflect.Constructor;
/**
* slf4j logger
*
* @author Nacos
*/
public class Slf4jLogger extends LoggerSupport implements Logger {
private static boolean CanUseEncoder = false;
private static final String LOGBACK_CLASSNAME = "ch.qos.logback.classic.Logger";
private static final String SLF4JLOG4J_CLASSNAME = "org.apache.logging.slf4j.Log4jLogger";
static {
try {
// logback从0.9.19开始采用encoder@see http://logback.qos.ch/manual/encoders.html
Class.forName("ch.qos.logback.classic.encoder.PatternLayoutEncoder");
CanUseEncoder = true;
} catch (ClassNotFoundException e) {
CanUseEncoder = false;
}
}
private org.slf4j.Logger delegate;
@SuppressWarnings("unchecked")
public Slf4jLogger(org.slf4j.Logger delegate) {
super(delegate);
if (delegate == null) {
throw new IllegalArgumentException("delegate Logger is null");
}
this.delegate = delegate;
String activateOptionClass = null;
if (LOGBACK_CLASSNAME.equals(delegate.getClass().getName())) {
if (CanUseEncoder) {
activateOptionClass = "com.alibaba.nacos.client.logger.option.LogbackActivateOption";
} else {
activateOptionClass = "com.alibaba.nacos.client.logger.option.Logback918ActivateOption";
}
} else if (SLF4JLOG4J_CLASSNAME.equals(delegate.getClass().getName())) {
activateOptionClass = "com.alibaba.nacos.client.logger.option.Slf4jLog4j2AdapterActivateOption";
}
if (activateOptionClass == null) {
throw new IllegalArgumentException("delegate must be logback impl or slf4j-log4j impl");
}
try {
Class<ActivateOption> clazz = (Class<ActivateOption>)Class.forName(activateOptionClass);
Constructor<ActivateOption> c = clazz.getConstructor(Object.class);
this.activateOption = c.newInstance(delegate);
} catch (Exception e) {
throw new IllegalArgumentException("delegate must be logback impl or slf4j-log4j impl", e);
}
}
@Override
public void debug(String context, String message) {
if (isDebugEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.debug(MessageUtil.getMessage(context, message));
}
}
@Override
public void debug(String context, String format, Object... args) {
if (isDebugEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.debug(MessageUtil.getMessage(context, format), args);
}
}
@Override
public void info(String context, String message) {
if (isInfoEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.info(MessageUtil.getMessage(context, message));
}
}
@Override
public void info(String context, String format, Object... args) {
if (isInfoEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.info(MessageUtil.getMessage(context, format), args);
}
}
@Override
public void warn(String message, Throwable t) {
if (isWarnEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.warn(MessageUtil.getMessage(null, message), t);
}
}
@Override
public void warn(String context, String message) {
if (isWarnEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.warn(MessageUtil.getMessage(context, message));
}
}
@Override
public void warn(String context, String format, Object... args) {
if (isWarnEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.warn(MessageUtil.getMessage(context, format), args);
}
}
@Override
public void error(String context, String errorCode, String message) {
if (isErrorEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.error(MessageUtil.getMessage(context, errorCode, message));
}
}
@Override
public void error(String context, String errorCode, String message, Throwable t) {
if (isErrorEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.error(MessageUtil.getMessage(context, errorCode, message), t);
}
}
@Override
public void error(String context, String errorCode, String format, Object... args) {
if (isErrorEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.error(MessageUtil.getMessage(context, errorCode, format), args);
}
}
@Override
public boolean isDebugEnabled() {
return delegate.isDebugEnabled();
}
@Override
public boolean isInfoEnabled() {
return delegate.isInfoEnabled();
}
@Override
public boolean isWarnEnabled() {
return delegate.isWarnEnabled();
}
@Override
public boolean isErrorEnabled() {
return delegate.isErrorEnabled();
}
}

View File

@ -1,51 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.slf4j;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.nop.NopLogger;
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
import com.alibaba.nacos.client.logger.support.LogLog;
/**
* Slf4jLogger Factory
*
* @author Nacos
*/
public class Slf4jLoggerFactory implements ILoggerFactory {
public Slf4jLoggerFactory() throws ClassNotFoundException {
Class.forName("org.slf4j.impl.StaticLoggerBinder");
}
public Logger getLogger(String name) {
try {
return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(name));
} catch (Throwable t) {
LogLog.error("Failed to get Slf4jLogger", t);
return new NopLogger();
}
}
public Logger getLogger(Class<?> clazz) {
try {
return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(clazz));
} catch (Throwable t) {
LogLog.error("Failed to get Slf4jLogger", t);
return new NopLogger();
}
}
}

View File

@ -1,48 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.support;
import java.util.HashMap;
/**
* @author zhuyong on 2017/6/30.
*/
public class AppenderInfo extends HashMap {
private static String name = "name";
private static String type = "type";
private static String file = "file";
public String getName() {
return (String)get(AppenderInfo.name);
}
public void setName(String name) {
put(AppenderInfo.name, name);
}
public void setType(String type) {
put(AppenderInfo.type, type);
}
public void setFile(String file) {
put(AppenderInfo.file, file);
}
public void withDetail(String name, Object value) {
put(name, value);
}
}

View File

@ -1,35 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
/*
* Copyright 2014 Alibaba.com All right reserved. This software is the
* confidential and proprietary information of Alibaba.com ("Confidential
* Information"). You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with Alibaba.com.
*/
package com.alibaba.nacos.client.logger.support;
/**
* 兼容老的ErrorLog后续请使用{@link LoggerHelper}
*
* @author zhuyong 2014年7月1日 上午11:41:22
*/
public class ErrorLog {
public static String buildErrorMsg(String msg, String errorCode, String errorType) {
return LoggerHelper.getErrorCodeStr(null, errorCode, errorType, msg);
}
}

View File

@ -1,41 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.support;
import com.alibaba.nacos.client.logger.Logger;
/**
* logger factory interface
*
* @author Nacos
*/
public interface ILoggerFactory {
/**
* get logger
*
* @param clazz class
* @return logger
*/
Logger getLogger(Class<?> clazz);
/**
* get logger
*
* @param name logger name
* @return logger
*/
Logger getLogger(String name);
}

View File

@ -1,144 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.support;
import java.io.PrintStream;
import java.util.Calendar;
/**
* logger log
*
* @author Nacos
*/
public class LogLog {
private static final String CLASS_INFO = LogLog.class.getClassLoader().toString();
private static boolean debugEnabled = false;
private static boolean infoEnabled = true;
private static boolean quietMode = false;
private static final String DEBUG_PREFIX = "JM.Log:DEBUG ";
private static final String INFO_PREFIX = "JM.Log:INFO ";
private static final String WARN_PREFIX = "JM.Log:WARN ";
private static final String ERR_PREFIX = "JM.Log:ERROR ";
public static void setQuietMode(boolean quietMode) {
LogLog.quietMode = quietMode;
}
static public void setInternalDebugging(boolean enabled) {
debugEnabled = enabled;
}
static public void setInternalInfoing(boolean enabled) {
infoEnabled = enabled;
}
public static void debug(String msg) {
if (debugEnabled && !quietMode) {
println(System.out, DEBUG_PREFIX + msg);
}
}
public static void debug(String msg, Throwable t) {
if (debugEnabled && !quietMode) {
println(System.out, DEBUG_PREFIX + msg);
if (t != null) {
t.printStackTrace(System.out);
}
}
}
public static void info(String msg) {
if (infoEnabled && !quietMode) {
println(System.out, INFO_PREFIX + msg);
}
}
public static void info(String msg, Throwable t) {
if (infoEnabled && !quietMode) {
println(System.out, INFO_PREFIX + msg);
if (t != null) {
t.printStackTrace(System.out);
}
}
}
public static void error(String msg) {
if (quietMode) {
return;
}
println(System.err, ERR_PREFIX + msg);
}
public static void error(String msg, Throwable t) {
if (quietMode) {
return;
}
println(System.err, ERR_PREFIX + msg);
if (t != null) {
t.printStackTrace();
}
}
public static void warn(String msg) {
if (quietMode) {
return;
}
println(System.err, WARN_PREFIX + msg);
}
public static void warn(String msg, Throwable t) {
if (quietMode) {
return;
}
println(System.err, WARN_PREFIX + msg);
if (t != null) {
t.printStackTrace();
}
}
private static void println(PrintStream out, String msg) {
out.println(Calendar.getInstance().getTime().toString() + " " + CLASS_INFO + " " + msg);
}
private static void outPrintln(PrintStream out, String msg) {
out.println(Calendar.getInstance().getTime().toString() + " " + CLASS_INFO + " " + msg);
}
}

View File

@ -1,230 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.support;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.AsyncAppenderBase;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.Layout;
import ch.qos.logback.core.OutputStreamAppender;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.encoder.LayoutWrappingEncoder;
import ch.qos.logback.core.pattern.Converter;
import ch.qos.logback.core.pattern.PatternLayoutBase;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.slf4j.ILoggerFactory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author zhuyong on 2017/6/28.
*/
public class LogbackHelper {
private static boolean Logback = false;
private static Field f, f1;
private static ILoggerFactory lcObject;
static {
try {
Class<?> loggerClass = Class.forName("ch.qos.logback.classic.Logger");
// 这里可能会加载到应用中依赖的logback因此需要判断classloader
if (loggerClass.getClassLoader().equals(LogbackHelper.class.getClassLoader())) {
ILoggerFactory lc = org.slf4j.LoggerFactory.getILoggerFactory();
if (!(lc instanceof LoggerContext)) {
LogLog.warn(
"expected logback binding with SLF4J, but another log system has taken the place: " + lcObject
.getClass().getSimpleName());
} else {
lcObject = lc;
f = PatternLayoutBase.class.getDeclaredField("head");
f.setAccessible(true);
f1 = ThrowableProxyConverter.class.getDeclaredField("lengthOption");
f1.setAccessible(true);
Logback = true;
}
}
} catch (Throwable t) {
LogLog.error("failed to init LogbackHelper, " + t.getMessage());
}
}
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
public static Boolean setDepth(int depth) {
if (Logback) {
if (depth == -1) {
depth = Integer.MAX_VALUE;
}
try {
LoggerContext loggerContext = (LoggerContext)lcObject;
List<Logger> loggers = loggerContext.getLoggerList();
for (ch.qos.logback.classic.Logger logger : loggers) {
Iterator<Appender<ILoggingEvent>> iter = logger.iteratorForAppenders();
doSetDepth(iter, depth);
}
} catch (Throwable t) {
LogLog.error("failed to set depth for logback", t);
return false;
}
LogLog.info("set logback throwable depth success, depth: " + depth);
return true;
}
return null;
}
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
public static Boolean changeLevel(String name, String level) {
if (Logback) {
try {
Level l = Level.toLevel(level, Level.ERROR);
LoggerContext loggerContext = (LoggerContext)lcObject;
Logger logger = loggerContext.exists(name);
if (logger != null) {
logger.setLevel(l);
LogLog.info("set logback log level success, " + name + ": " + l);
return true;
}
LogLog.info("set logback log level fail, no logger name exists: " + name);
} catch (Throwable t) {
LogLog.error("failed to change level for logback, " + name + ": " + level, t);
}
return false;
}
return null;
}
public static Map<String, LoggerInfo> getLoggers(String name) {
Map<String, LoggerInfo> appenders = new HashMap<String, LoggerInfo>(10);
if (Logback) {
LoggerContext loggerContext = (LoggerContext)lcObject;
if (name != null && !"".equals(name.trim())) {
Logger logger = loggerContext.exists(name);
if (logger != null) {
appenders.put(name, doGetLoggerInfo(logger));
}
} else {
// 获取所有logger时如果没有appender则忽略
List<Logger> loggers = loggerContext.getLoggerList();
for (Logger logger : loggers) {
LoggerInfo info = doGetLoggerInfo(logger);
if (info.getAppenders() == null || !info.getAppenders().isEmpty()) {
appenders.put(logger.getName(), info);
}
}
}
}
return appenders;
}
private static void doSetDepth(Iterator<Appender<ILoggingEvent>> iter, int depth)
throws IllegalAccessException {
while (iter.hasNext()) {
Appender<ILoggingEvent> a = iter.next();
if (a instanceof AsyncAppenderBase) {
Iterator<Appender<ILoggingEvent>> aiter = ((AsyncAppenderBase)a).iteratorForAppenders();
doSetDepth(aiter, depth);
} else if (a instanceof OutputStreamAppender) {
OutputStreamAppender oa = (OutputStreamAppender)a;
Encoder e = oa.getEncoder();
Layout l = null;
if (e instanceof PatternLayoutEncoder) {
l = ((PatternLayoutEncoder)e).getLayout();
} else if (e instanceof LayoutWrappingEncoder) {
l = ((LayoutWrappingEncoder)e).getLayout();
}
if (l != null) {
if (l instanceof PatternLayoutBase) {
Converter c = (Converter)f.get(l);
while (c != null) {
if (c instanceof ThrowableProxyConverter) {
f1.set(c, depth);
break;
}
c = c.getNext();
}
}
}
}
}
}
private static LoggerInfo doGetLoggerInfo(Logger logger) {
LoggerInfo info = new LoggerInfo(logger.getName(), logger.isAdditive());
Level level = logger.getLevel(), effectiveLevel = logger.getEffectiveLevel();
if (level != null) {
info.setLevel(level.toString());
}
if (effectiveLevel != null) {
info.setEffectiveLevel(effectiveLevel.toString());
}
List<AppenderInfo> result = doGetLoggerAppenders(logger.iteratorForAppenders());
info.setAppenders(result);
return info;
}
private static List<AppenderInfo> doGetLoggerAppenders(Iterator<Appender<ILoggingEvent>> appenders) {
List<AppenderInfo> result = new ArrayList<AppenderInfo>();
while (appenders.hasNext()) {
AppenderInfo info = new AppenderInfo();
Appender<ILoggingEvent> appender = appenders.next();
info.setName(appender.getName());
info.setType(appender.getClass().getName());
if (appender instanceof FileAppender) {
info.setFile(((FileAppender)appender).getFile());
} else if (appender instanceof AsyncAppender) {
AsyncAppender aa = (AsyncAppender)appender;
Iterator<Appender<ILoggingEvent>> iter = aa.iteratorForAppenders();
List<AppenderInfo> asyncs = doGetLoggerAppenders(iter);
// 标明异步appender
List<String> nestedNames = new ArrayList<String>();
for (AppenderInfo a : asyncs) {
nestedNames.add(a.getName());
result.add(a);
}
info.withDetail("nestedNames", nestedNames);
} else if (appender instanceof ConsoleAppender) {
info.withDetail("target", ((ConsoleAppender)appender).getTarget());
}
result.add(info);
}
return result;
}
}

View File

@ -1,252 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.support;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.FileAppender;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.nacos.client.logger.Logger;
/**
* logger help
*
* @author Nacos
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class LoggerHelper {
private static final String MORE_URL_POSFIX = ".ERROR_CODE_MORE_URL";
private static final String DEFAULT_MORE_URL = "http://console.taobao.net/help/";
private static String LOG_PATH = null;
private static final String CONVERSION_PATTERN = "01 %d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n";
private static Map<String, Boolean> Product_Logger_Info;
private static Map<String, String> Product_Logger_Pattern;
private static Map<String, ResourceBundle> Product_Resource_Bundle;
static {
String dpath = System.getProperty("JM.LOG.PATH");
if (dpath == null || dpath.trim().equals("")) {
String defaultPath = System.getProperty("user.home");
LOG_PATH = defaultPath + File.separator + "logs" + File.separator;
} else {
if (!new File(dpath).isAbsolute()) {
// throw new RuntimeException("-DJM.LOG.PATH must be an absolute path.");
String defaultPath = System.getProperty("user.home");
dpath = defaultPath + File.separator + dpath;
}
if (dpath.endsWith(File.separator)) {
LOG_PATH = dpath;
} else {
LOG_PATH = dpath + File.separator;
}
}
LogLog.info("Log root path: " + LOG_PATH);
Product_Logger_Info = new ConcurrentHashMap<String, Boolean>();
Product_Logger_Pattern = new ConcurrentHashMap<String, String>();
Product_Resource_Bundle = new ConcurrentHashMap<String, ResourceBundle>();
}
/**
* 获取中间件日志根目录以File.separator结尾
*/
public static String getLogpath() {
return LOG_PATH;
}
/**
* <pre>
* 获取中间件产品日志路径
*
* 优先使用-DJM.LOG.PATH参数且必须是绝对路径
* 其次是{user.home}/logs/
*
* 比如hsf调用LoggerHelper.getLogFile("hsf", "hsf.log")则返回{user.home}/logs/hsf/hsf.log
* </pre>
*
* @param productName 中间件产品名如hsf, tddl
* @param fileName 日志文件名如hsf.log如需要二级子目录可以传 subDir + File.separator + *.log
*/
public static String getLogFile(String productName, String fileName) {
String file = LOG_PATH + productName + File.separator + fileName;
if (Product_Logger_Info.get(productName) == null) {
Product_Logger_Info.put(productName, true);
LogLog.info("Set " + productName + " log path: " + LOG_PATH + productName);
}
return file;
}
/**
* 获取中间件日志格式优先使用用户产品自定义的格式logback/log4j通用
*/
public static String getPattern(String productName) {
String pattern = Product_Logger_Pattern.get(productName);
if (pattern == null) {
return CONVERSION_PATTERN;
}
return pattern;
}
/**
* 获取中间件日志特定格式
*/
public static String getPattern() {
return CONVERSION_PATTERN;
}
/**
* 设置特定中间件产品的日志格式注意这里的格式需要自己保证在 log4j/logback 下都兼容框架不做校验同时控制台输出仍会采用中间件的特定格式
*
* @param productName 中间件产品名如hsf, tddl
* @param pattern 日志格式
*/
public static void setPattern(String productName, String pattern) {
Product_Logger_Pattern.put(productName, pattern);
}
/**
* 设置产品的日志国际化properties文件
*
* @param productName 中间件产品名如hsf, tddl
* @param bundleName bundleName
*/
public static void setResourceBundle(String productName, String bundleName) {
try {
ResourceBundle rb = ResourceBundle.getBundle(bundleName);
Product_Resource_Bundle.put(productName, rb);
} catch (Exception e) {
LogLog.error("Failed to set " + productName + " resource bundle for: " + bundleName, e);
}
}
/**
* 获取国际化的message如果找不到则返回原始的code
*
* @param productName 中间件产品名如hsf, tddl
* @param code code
*/
public static String getResourceBundleString(String productName, String code) {
if (Product_Resource_Bundle.isEmpty() || code == null || productName == null) {
return code;
}
ResourceBundle rs = Product_Resource_Bundle.get(productName);
if (rs != null) {
try {
String value = rs.getString(code);
return value;
} catch (MissingResourceException e) {
return code;
}
}
return code;
}
/**
* 获取统一格式的ErrorCode输出
*
* @param errorCode
*/
@Deprecated
public static String getErrorCodeStr(String errorCode) {
return "ERR-CODE: [" + errorCode + "], More: [" + "http://console.taobao.net/jm/" + errorCode + "]";
}
/**
* 根据productName获取统一格式的ErrorCode输出
*
* @param productName HSF会根据 HSF.ErrorCodeMoreUrl System属性中获取 more url 前缀如http://console.taobao.net/jm/
* @param errorCode 错误码如HSF-001
* @param errorType 错误类型
* @param message 出错异常信息
*/
public static String getErrorCodeStr(String productName, String errorCode, String errorType, String message) {
String moreUrl = DEFAULT_MORE_URL;
if (productName != null) {
String customUrl = System.getProperty(productName.toUpperCase() + MORE_URL_POSFIX);
if (customUrl != null) {
moreUrl = customUrl;
}
}
StringBuilder sb = new StringBuilder();
sb.append(message);
sb.append(" ERR-CODE: [");
sb.append(errorCode);
sb.append("], Type: [");
sb.append(errorType);
sb.append("], More: [");
sb.append(moreUrl);
sb.append(errorCode);
sb.append("]");
return sb.toString();
}
@SuppressFBWarnings(value = {"RV_RETURN_VALUE_IGNORED_BAD_PRACTICE"})
public static String getLogFileP(String productName, String fileName) {
String file = getLogFile(productName, fileName);
File logfile = new File(file);
logfile.getParentFile().mkdirs();
return file;
}
/**
* When prudent is set to true, file appenders from multiple JVMs can safely write to the same file.
* <p>
* Only support by logback
*
* @param prudent
* @since 0.1.8
*/
public static void activePrudent(Logger logger, boolean prudent) {
if (logger != null && logger.getDelegate() != null) {
if (!(logger.getDelegate() instanceof ch.qos.logback.classic.Logger)) {
throw new IllegalArgumentException("logger must be ch.qos.logback.classic.Logger, but it's "
+ logger.getDelegate().getClass());
}
Iterator<Appender<ILoggingEvent>> iter = ((ch.qos.logback.classic.Logger)logger.getDelegate())
.iteratorForAppenders();
while (iter.hasNext()) {
ch.qos.logback.core.Appender<ILoggingEvent> appender = iter.next();
if (appender instanceof FileAppender) {
((FileAppender)appender).setPrudent(prudent);
} else {
continue;
}
}
}
}
}

View File

@ -1,54 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.support;
import java.util.HashMap;
import java.util.List;
/**
* @author zhuyong on 2017/06/29
*/
public class LoggerInfo extends HashMap {
private static String level = "level";
private static String effectiveLevel = "effectiveLevel";
private static String additivity = "additivity";
private static String appenders = "appenders";
public LoggerInfo(String name, boolean additivity) {
put(LoggerInfo.additivity, additivity);
}
public void setLevel(String level) {
put(LoggerInfo.level, level);
}
public void setEffectiveLevel(String effectiveLevel) {
put(LoggerInfo.effectiveLevel, effectiveLevel);
}
public String getLevel() {
return (String)get(level);
}
public List<AppenderInfo> getAppenders() {
return (List<AppenderInfo>)get(appenders);
}
public void setAppenders(List<AppenderInfo> appenders) {
put(LoggerInfo.appenders, appenders);
}
}

View File

@ -1,200 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.support;
import java.util.List;
import java.util.Map;
import com.alibaba.nacos.client.logger.Level;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.option.ActivateOption;
/**
* Logger Support
*
* @author Nacos
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class LoggerSupport implements Logger {
protected Object delegateLogger;
protected ActivateOption activateOption;
public LoggerSupport(Object delegate) {
this.delegateLogger = delegate;
}
@Override
public void debug(String message) {
debug(null, message);
}
@Override
public void debug(String format, Object... args) {
debug(null, format, args);
}
@Override
public void info(String message) {
info(null, message);
}
@Override
public void info(String format, Object... args) {
info(null, format, args);
}
@Override
public void warn(String message) {
warn(null, message);
}
@Override
public void warn(String format, Object... args) {
warn(null, format, args);
}
@Override
public void error(String errorCode, String message) {
error(null, errorCode, message);
}
@Override
public void error(String errorCode, String message, Throwable t) {
error(null, errorCode, message, t);
}
@Override
public void error(String errorCode, String format, Object... args) {
error(null, errorCode, format, args);
}
public Object getDelegate() {
return delegateLogger;
}
public void activateConsoleAppender(String target, String encoding) {
if (activateOption != null) {
activateOption.activateConsoleAppender(target, encoding);
}
}
@Override
public void activateAppender(String productName, String file, String encoding) {
if (activateOption != null) {
activateOption.activateAppender(productName, file, encoding);
}
}
@Override
public void setLevel(Level level) {
if (activateOption != null) {
activateOption.setLevel(level);
}
}
@Override
public Level getLevel() {
if (activateOption != null) {
return activateOption.getLevel();
}
return null;
}
@Override
public void setAdditivity(boolean additivity) {
if (activateOption != null) {
activateOption.setAdditivity(additivity);
}
}
@Override
public String getProductName() {
if (activateOption != null) {
return activateOption.getProductName();
}
return null;
}
@Override
public void activateAsyncAppender(String productName, String file, String encoding) {
if (activateOption != null) {
activateOption.activateAsyncAppender(productName, file, encoding);
}
}
@Override
public void activateAsyncAppender(String productName, String file, String encoding, int queueSize,
int discardingThreshold) {
if (activateOption != null) {
activateOption.activateAsyncAppender(productName, file, encoding, queueSize, discardingThreshold);
}
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size) {
if (activateOption != null) {
activateOption.activateAppenderWithTimeAndSizeRolling(productName, file, encoding, size);
}
}
@Override
public void activateAppender(Logger logger) {
if (activateOption != null) {
activateOption.activateAppender(logger);
}
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern) {
if (activateOption != null) {
activateOption.activateAppenderWithTimeAndSizeRolling(productName, file, encoding, size, datePattern);
}
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern, int maxBackupIndex) {
if (activateOption != null) {
activateOption.activateAppenderWithTimeAndSizeRolling(productName, file, encoding, size, datePattern,
maxBackupIndex);
}
}
@Override
public void activateAppenderWithSizeRolling(String productName, String file, String encoding, String size,
int maxBackupIndex) {
if (activateOption != null) {
activateOption.activateAppenderWithSizeRolling(productName, file, encoding, size, maxBackupIndex);
}
}
@Override
public void activateAsync(int queueSize, int discardingThreshold) {
if (activateOption != null) {
activateOption.activateAsync(queueSize, discardingThreshold);
}
}
@Override
public void activateAsync(List<Object[]> args) {
if (activateOption != null) {
activateOption.activateAsync(args);
}
}
}

View File

@ -1,67 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.util;
/**
* Holds the results of formatting done by {@link MessageFormatter}.
*
* @author Joern Huxhorn
*/
public class FormattingTuple {
static public FormattingTuple NULL = new FormattingTuple(null);
private String message;
private Throwable throwable;
private Object[] argArray;
public FormattingTuple(String message) {
this(message, null, null);
}
public FormattingTuple(String message, Object[] argArray, Throwable throwable) {
this.message = message;
this.throwable = throwable;
if (throwable == null) {
this.argArray = argArray.clone();
} else {
this.argArray = trimmedCopy(argArray);
}
}
static Object[] trimmedCopy(Object[] argArray) {
if (argArray == null || argArray.length == 0) {
throw new IllegalStateException("non-sensical empty or null argument array");
}
final int trimemdLen = argArray.length - 1;
Object[] trimmed = new Object[trimemdLen];
System.arraycopy(argArray, 0, trimmed, 0, trimemdLen);
return trimmed;
}
public String getMessage() {
return message;
}
public Object[] getArgArray() {
return argArray.clone();
}
public Throwable getThrowable() {
return throwable;
}
}

View File

@ -1,400 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.util;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
// contributors: lizongbo: proposed special treatment of array parameter values
// Joern Huxhorn: pointed out double[] omission, suggested deep array copy
/**
* Formats messages according to very simple substitution rules. Substitutions can be made 1, 2 or more arguments.
* <p>
* <p>
* For example,
* <p>
* <pre>
* MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;)
* </pre>
* <p>
* will return the string "Hi there.".
* <p>
* The {} pair is called the <em>formatting anchor</em>. It serves to designate the location where arguments need to be
* substituted within the message pattern.
* <p>
* In case your message contains the '{' or the '}' character, you do not have to do anything special unless the '}'
* character immediately follows '{'. For example,
* <p>
* <pre>
* MessageFormatter.format(&quot;Set {1,2,3} is not equal to {}.&quot;, &quot;1,2&quot;);
* </pre>
* <p>
* will return the string "Set {1,2,3} is not equal to 1,2.".
* <p>
* <p>
* If for whatever reason you need to place the string "{}" in the message without its <em>formatting anchor</em>
* meaning, then you need to escape the '{' character with '\', that is the backslash character. Only the '{' character
* should be escaped. There is no need to escape the '}' character. For example,
* <p>
* <pre>
* MessageFormatter.format(&quot;Set \\{} is not equal to {}.&quot;, &quot;1,2&quot;);
* </pre>
* <p>
* will return the string "Set {} is not equal to 1,2.".
* <p>
* <p>
* The escaping behavior just described can be overridden by escaping the escape character '\'. Calling
* <p>
* <pre>
* MessageFormatter.format(&quot;File name is C:\\\\{}.&quot;, &quot;file.zip&quot;);
* </pre>
* <p>
* will return the string "File name is C:\file.zip".
* <p>
* <p>
* The formatting conventions are different than those of {@link MessageFormat} which ships with the Java platform. This
* is justified by the fact that SLF4J's implementation is 10 times faster than that of {@link MessageFormat}. This
* local performance difference is both measurable and significant in the larger context of the complete logging
* processing chain.
* <p>
* <p>
* See also {@link #format(String, Object)}, {@link #format(String, Object, Object)} and {@link #arrayFormat(String,
* Object[])} methods for more details.
*
* @author Ceki G&uuml;lc&uuml;
* @author Joern Huxhorn
*/
final public class MessageFormatter {
static final char DELIM_START = '{';
static final char DELIM_STOP = '}';
static final String DELIM_STR = "{}";
private static final char ESCAPE_CHAR = '\\';
private static int DELIMETER_START_INDEX = 2;
/**
* Performs single argument substitution for the 'messagePattern' passed as parameter.
* <p>
* For example,
* <p>
* <pre>
* MessageFormatter.format(&quot;Hi {}.&quot;, &quot;there&quot;);
* </pre>
* <p>
* will return the string "Hi there.".
* <p>
*
* @param messagePattern The message pattern which will be parsed and formatted
* @param argument The argument to be substituted in place of the formatting anchor
* @return The formatted message
*/
final public static FormattingTuple format(String messagePattern, Object arg) {
return arrayFormat(messagePattern, new Object[] {arg});
}
/**
* Performs a two argument substitution for the 'messagePattern' passed as parameter.
* <p>
* For example,
* <p>
* <pre>
* MessageFormatter.format(&quot;Hi {}. My name is {}.&quot;, &quot;Alice&quot;, &quot;Bob&quot;);
* </pre>
* <p>
* will return the string "Hi Alice. My name is Bob.".
*
* @param messagePattern The message pattern which will be parsed and formatted
* @param arg1 The argument to be substituted in place of the first formatting anchor
* @param arg2 The argument to be substituted in place of the second formatting anchor
* @return The formatted message
*/
final public static FormattingTuple format(final String messagePattern,
Object arg1, Object arg2) {
return arrayFormat(messagePattern, new Object[] {arg1, arg2});
}
static final Throwable getThrowableCandidate(Object[] argArray) {
if (argArray == null || argArray.length == 0) {
return null;
}
final Object lastEntry = argArray[argArray.length - 1];
if (lastEntry instanceof Throwable) {
return (Throwable)lastEntry;
}
return null;
}
/**
* Same principle as the {@link #format(String, Object)} and {@link #format(String, Object, Object)} methods except
* that any number of arguments can be passed in an array.
*
* @param messagePattern The message pattern which will be parsed and formatted
* @param argArray An array of arguments to be substituted in place of formatting anchors
* @return The formatted message
*/
final public static FormattingTuple arrayFormat(final String messagePattern,
final Object[] argArray) {
Throwable throwableCandidate = getThrowableCandidate(argArray);
if (messagePattern == null) {
return new FormattingTuple(null, argArray, throwableCandidate);
}
if (argArray == null) {
return new FormattingTuple(messagePattern);
}
int i = 0;
int j;
StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50);
int lenTmp;
for (lenTmp = 0; lenTmp < argArray.length; lenTmp++) {
j = messagePattern.indexOf(DELIM_STR, i);
if (j == -1) {
// no more variables
if (i == 0) {
return new FormattingTuple(messagePattern, argArray,
throwableCandidate);
} else {
sbuf.append(messagePattern.substring(i, messagePattern.length()));
return new FormattingTuple(sbuf.toString(), argArray,
throwableCandidate);
}
} else {
if (isEscapedDelimeter(messagePattern, j)) {
if (!isDoubleEscaped(messagePattern, j)) {
lenTmp--; // DELIM_START was escaped, thus should not be incremented
sbuf.append(messagePattern.substring(i, j - 1));
sbuf.append(DELIM_START);
i = j + 1;
} else {
// The escape character preceding the delimiter start is
// itself escaped: "abc x:\\{}"
// we have to consume one backward slash
sbuf.append(messagePattern.substring(i, j - 1));
deeplyAppendParameter(sbuf, argArray[lenTmp], new HashMap(10));
i = j + 2;
}
} else {
// normal case
sbuf.append(messagePattern.substring(i, j));
deeplyAppendParameter(sbuf, argArray[lenTmp], new HashMap(10));
i = j + 2;
}
}
}
// append the characters following the last {} pair.
sbuf.append(messagePattern.substring(i, messagePattern.length()));
if (lenTmp < argArray.length - 1) {
return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate);
} else {
return new FormattingTuple(sbuf.toString(), argArray, null);
}
}
final static boolean isEscapedDelimeter(String messagePattern,
int delimeterStartIndex) {
if (delimeterStartIndex == 0) {
return false;
}
char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
if (potentialEscape == ESCAPE_CHAR) {
return true;
} else {
return false;
}
}
final static boolean isDoubleEscaped(String messagePattern,
int delimeterStartIndex) {
if (delimeterStartIndex >= DELIMETER_START_INDEX
&& messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) {
return true;
} else {
return false;
}
}
private static void deeplyAppendParameter(StringBuffer sbuf, Object o,
Map seenMap) {
if (o == null) {
sbuf.append("null");
return;
}
if (!o.getClass().isArray()) {
safeObjectAppend(sbuf, o);
} else {
// check for primitive array types because they
// unfortunately cannot be cast to Object[]
if (o instanceof boolean[]) {
booleanArrayAppend(sbuf, (boolean[])o);
} else if (o instanceof byte[]) {
byteArrayAppend(sbuf, (byte[])o);
} else if (o instanceof char[]) {
charArrayAppend(sbuf, (char[])o);
} else if (o instanceof short[]) {
shortArrayAppend(sbuf, (short[])o);
} else if (o instanceof int[]) {
intArrayAppend(sbuf, (int[])o);
} else if (o instanceof long[]) {
longArrayAppend(sbuf, (long[])o);
} else if (o instanceof float[]) {
floatArrayAppend(sbuf, (float[])o);
} else if (o instanceof double[]) {
doubleArrayAppend(sbuf, (double[])o);
} else {
objectArrayAppend(sbuf, (Object[])o, seenMap);
}
}
}
private static void safeObjectAppend(StringBuffer sbuf, Object o) {
try {
String oAsString = o.toString();
sbuf.append(oAsString);
} catch (Throwable t) {
System.err
.println("SLF4J: Failed toString() invocation on an object of type ["
+ o.getClass().getName() + "]");
t.printStackTrace();
sbuf.append("[FAILED toString()]");
}
}
private static void objectArrayAppend(StringBuffer sbuf, Object[] a,
Map seenMap) {
sbuf.append('[');
if (!seenMap.containsKey(a)) {
seenMap.put(a, null);
final int len = a.length;
for (int i = 0; i < len; i++) {
deeplyAppendParameter(sbuf, a[i], seenMap);
if (i != len - 1) {
sbuf.append(", ");
}
}
// allow repeats in siblings
seenMap.remove(a);
} else {
sbuf.append("...");
}
sbuf.append(']');
}
private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void byteArrayAppend(StringBuffer sbuf, byte[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void charArrayAppend(StringBuffer sbuf, char[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void shortArrayAppend(StringBuffer sbuf, short[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void intArrayAppend(StringBuffer sbuf, int[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void longArrayAppend(StringBuffer sbuf, long[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void floatArrayAppend(StringBuffer sbuf, float[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void doubleArrayAppend(StringBuffer sbuf, double[] a) {
sbuf.append('[');
final int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
}

View File

@ -1,48 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logger.util;
/**
* Error msg format
*
* @author Nacos
*/
public class MessageUtil {
public static String formatMessage(String format, Object[] argArray) {
FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
return ft.getMessage();
}
public static String getMessage(String message) {
return getMessage(null, message);
}
public static String getMessage(String context, String message) {
return getMessage(context, null, message);
}
public static String getMessage(String context, String errorCode, String message) {
if (context == null) {
context = "";
}
if (errorCode == null) {
errorCode = "";
}
return "[" + context + "] [] [" + errorCode + "] " + message;
}
}

View File

@ -0,0 +1,52 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logging;
import com.alibaba.nacos.client.utils.StringUtils;
import org.apache.commons.lang3.BooleanUtils;
/**
* @author <a href="mailto:huangxiaoyu1018@gmail.com">hxy1991</a>
* @since 0.9.0
*/
public abstract class AbstractNacosLogging {
private static final String NACOS_LOGGING_CONFIG_PROPERTY = "nacos.logging.config";
private static final String NACOS_LOGGING_DEFAULT_CONFIG_ENABLED_PROPERTY = "nacos.logging.default.config.enabled";
protected String getLocation(String defaultLocation) {
String location = System.getProperty(NACOS_LOGGING_CONFIG_PROPERTY);
if (StringUtils.isBlank(location)) {
if (isDefaultConfigEnabled()) {
return defaultLocation;
}
return null;
}
return location;
}
private boolean isDefaultConfigEnabled() {
String property = System.getProperty(NACOS_LOGGING_DEFAULT_CONFIG_ENABLED_PROPERTY);
// The default value is true.
return property == null || BooleanUtils.toBoolean(property);
}
/**
* Load logging configuration
*/
public abstract void loadConfiguration();
}

View File

@ -0,0 +1,136 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logging.log4j2;
import com.alibaba.nacos.client.logging.AbstractNacosLogging;
import com.alibaba.nacos.client.utils.StringUtils;
import com.alibaba.nacos.common.util.ClassUtils;
import com.alibaba.nacos.common.util.ResourceUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.AbstractConfiguration;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.composite.CompositeConfiguration;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Support for Log4j version 2.7 or higher
*
* @author <a href="mailto:huangxiaoyu1018@gmail.com">hxy1991</a>
* @since 0.9.0
*/
public class Log4J2NacosLogging extends AbstractNacosLogging {
private static final String NACOS_LOG4J2_LOCATION = "classpath:nacos-log4j2.xml";
private static final String FILE_PROTOCOL = "file";
private static final String YAML_PARSER_CLASS_NAME = "com.fasterxml.jackson.dataformat.yaml.YAMLParser";
private static final String JSON_PARSER_CLASS_NAME = "com.fasterxml.jackson.databind.ObjectMapper";
private Set<String> locationList = new HashSet<String>();
public Log4J2NacosLogging() {
String location = getLocation(NACOS_LOG4J2_LOCATION);
if (!StringUtils.isBlank(location)) {
locationList.add(location);
}
}
@Override
public void loadConfiguration() {
String config = findConfig(getCurrentlySupportedConfigLocations());
if (config != null) {
locationList.add(config);
}
final List<AbstractConfiguration> configurations = new ArrayList<AbstractConfiguration>();
LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false);
for (String location : locationList) {
try {
Configuration configuration = loadConfiguration(loggerContext, location);
if (configuration instanceof AbstractConfiguration) {
configurations.add((AbstractConfiguration)configuration);
}
} catch (Exception e) {
throw new IllegalStateException(
"Could not initialize Log4J2 Nacos logging from " + location, e);
}
}
// since log4j 2.6
CompositeConfiguration compositeConfiguration = new CompositeConfiguration(configurations);
loggerContext.start(compositeConfiguration);
}
private Configuration loadConfiguration(LoggerContext loggerContext, String location) {
try {
URL url = ResourceUtils.getResourceURL(location);
ConfigurationSource source = getConfigurationSource(url);
// since log4j 2.7 getConfiguration(LoggerContext loggerContext, ConfigurationSource source)
return ConfigurationFactory.getInstance().getConfiguration(loggerContext, source);
} catch (Exception e) {
throw new IllegalStateException(
"Could not initialize Log4J2 logging from " + location, e);
}
}
private ConfigurationSource getConfigurationSource(URL url) throws IOException {
InputStream stream = url.openStream();
if (FILE_PROTOCOL.equals(url.getProtocol())) {
return new ConfigurationSource(stream, ResourceUtils.getResourceAsFile(url));
}
return new ConfigurationSource(stream, url);
}
private String[] getCurrentlySupportedConfigLocations() {
List<String> supportedConfigLocations = new ArrayList<String>();
if (ClassUtils.isPresent(YAML_PARSER_CLASS_NAME)) {
Collections.addAll(supportedConfigLocations, "log4j2.yaml", "log4j2.yml");
}
if (ClassUtils.isPresent(JSON_PARSER_CLASS_NAME)) {
Collections.addAll(supportedConfigLocations, "log4j2.json", "log4j2.jsn");
}
supportedConfigLocations.add("log4j2.xml");
return supportedConfigLocations.toArray(new String[supportedConfigLocations.size()]);
}
private String findConfig(String[] locations) {
for (String location : locations) {
ClassLoader defaultClassLoader = ClassUtils.getDefaultClassLoader();
if (defaultClassLoader != null && defaultClassLoader.getResource(location) != null) {
return "classpath:" + location;
}
}
return null;
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.logging.logback;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.util.ContextInitializer;
import com.alibaba.nacos.client.logging.AbstractNacosLogging;
import com.alibaba.nacos.client.utils.StringUtils;
import com.alibaba.nacos.common.util.ResourceUtils;
import org.slf4j.impl.StaticLoggerBinder;
/**
* Support for Logback version 1.0.8 or higher
*
* @author <a href="mailto:huangxiaoyu1018@gmail.com">hxy1991</a>
* @since 0.9.0
*/
public class LogbackNacosLogging extends AbstractNacosLogging {
private static final String NACOS_LOGBACK_LOCATION = "classpath:nacos-logback.xml";
@Override
public void loadConfiguration() {
String location = getLocation(NACOS_LOGBACK_LOCATION);
if (StringUtils.isBlank(location)) {
return;
}
try {
LoggerContext loggerContext = (LoggerContext)StaticLoggerBinder.getSingleton().getLoggerFactory();
new ContextInitializer(loggerContext).configureByResource(ResourceUtils.getResourceURL(location));
} catch (Exception e) {
throw new IllegalStateException("Could not initialize Logback Nacos logging from " + location, e);
}
}
}

View File

@ -15,14 +15,8 @@
*/
package com.alibaba.nacos.client.monitor;
import io.micrometer.core.instrument.ImmutableTag;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import io.prometheus.client.Gauge;
import io.prometheus.client.Histogram;
/**
* Metrics Monitor
@ -30,52 +24,33 @@ import java.util.concurrent.atomic.AtomicInteger;
* @author Nacos
*/
public class MetricsMonitor {
private static AtomicInteger serviceInfoMapSize = new AtomicInteger();
private static AtomicInteger dom2BeatSize = new AtomicInteger();
private static AtomicInteger listenConfigCount = new AtomicInteger();
private static Gauge nacosMonitor = Gauge.build()
.name("nacos_monitor").labelNames("module", "name")
.help("nacos_monitor").register();
static {
List<Tag> tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "naming"));
tags.add(new ImmutableTag("name", "subServiceCount"));
Metrics.gauge("nacos_monitor", tags, serviceInfoMapSize);
private static Histogram nacosClientRequestHistogram = Histogram.build().labelNames("module", "method", "url", "code")
.name("nacos_client_request").help("nacos_client_request")
.register();
tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "naming"));
tags.add(new ImmutableTag("name", "pubServiceCount"));
Metrics.gauge("nacos_monitor", tags, dom2BeatSize);
tags = new ArrayList<Tag>();
tags.add(new ImmutableTag("module", "config"));
tags.add(new ImmutableTag("name", "listenConfigCount"));
Metrics.gauge("nacos_monitor", tags, listenConfigCount);
public static Gauge.Child getServiceInfoMapSizeMonitor() {
return nacosMonitor.labels("naming", "serviceInfoMapSize");
}
public static AtomicInteger getServiceInfoMapSizeMonitor() {
return serviceInfoMapSize;
public static Gauge.Child getDom2BeatSizeMonitor() {
return nacosMonitor.labels("naming", "dom2BeatSize");
}
public static AtomicInteger getDom2BeatSizeMonitor() {
return dom2BeatSize;
public static Gauge.Child getListenConfigCountMonitor() {
return nacosMonitor.labels("naming", "listenConfigCount");
}
public static AtomicInteger getListenConfigCountMonitor() {
return listenConfigCount;
public static Histogram.Timer getConfigRequestMonitor(String method, String url, String code) {
return nacosClientRequestHistogram.labels("config", method, url, code).startTimer();
}
public static Timer getConfigRequestMonitor(String method, String url, String code) {
return Metrics.timer("nacos_client_request",
"module", "config",
"method", method,
"url", url,
"code", code);
}
public static Timer getNamingRequestMonitor(String method, String url, String code) {
return Metrics.timer("nacos_client_request",
"module", "naming",
"method", method,
"url", url,
"code", code);
public static Histogram.Child getNamingRequestMonitor(String method, String url, String code) {
return nacosClientRequestHistogram.labels("naming", method, url, code);
}
}

View File

@ -31,7 +31,6 @@ import com.alibaba.nacos.client.naming.core.EventDispatcher;
import com.alibaba.nacos.client.naming.core.HostReactor;
import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import org.apache.commons.lang3.BooleanUtils;
@ -82,13 +81,6 @@ public class NacosNamingService implements NamingService {
logName = "naming.log";
}
String logLevel = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_LEVEL);
if (StringUtils.isEmpty(logLevel)) {
logLevel = "INFO";
}
LogUtils.setLogLevel(logLevel);
cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir");
if (StringUtils.isEmpty(cacheDir)) {
cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace;
@ -132,7 +124,8 @@ public class NacosNamingService implements NamingService {
properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START));
}
int clientBeatThreadCount = NumberUtils.toInt(properties.getProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT),
int clientBeatThreadCount = NumberUtils.toInt(
properties.getProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT),
UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT);
int pollingThreadCount = NumberUtils.toInt(properties.getProperty(PropertyKeyConst.NAMING_POLLING_THREAD_COUNT),
@ -205,7 +198,8 @@ public class NacosNamingService implements NamingService {
}
@Override
public List<Instance> getAllInstances(String serviceName, List<String> clusters, boolean subscribe) throws NacosException {
public List<Instance> getAllInstances(String serviceName, List<String> clusters, boolean subscribe)
throws NacosException {
ServiceInfo serviceInfo;
if (subscribe) {
@ -226,7 +220,8 @@ public class NacosNamingService implements NamingService {
}
@Override
public List<Instance> selectInstances(String serviceName, boolean healthy, boolean subscribe) throws NacosException {
public List<Instance> selectInstances(String serviceName, boolean healthy, boolean subscribe)
throws NacosException {
return selectInstances(serviceName, new ArrayList<String>(), healthy, subscribe);
}
@ -264,7 +259,8 @@ public class NacosNamingService implements NamingService {
}
@Override
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters, boolean subscribe) throws NacosException {
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters, boolean subscribe)
throws NacosException {
if (subscribe) {
return Balancer.RandomByWeight.selectHost(
@ -303,7 +299,8 @@ public class NacosNamingService implements NamingService {
}
@Override
public ListView<String> getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) throws NacosException {
public ListView<String> getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector)
throws NacosException {
return serverProxy.getServiceList(pageNo, pageSize, selector);
}

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.client.naming.cache.ConcurrentDiskUtil;
import com.alibaba.nacos.client.naming.cache.DiskCache;
import com.alibaba.nacos.client.naming.core.HostReactor;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
@ -32,6 +31,8 @@ import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.*;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
@ -83,7 +84,7 @@ public class FailoverReactor {
new DiskFileWriter().run();
}
} catch (Throwable e) {
LogUtils.LOG.error("NA", "failed to backup file on startup.", e);
NAMING_LOGGER.error("[NA] failed to backup file on startup.", e);
}
}
@ -106,7 +107,7 @@ public class FailoverReactor {
File switchFile = new File(failoverDir + UtilAndComs.FAILOVER_SWITCH);
if (!switchFile.exists()) {
switchParams.put("failover-mode", "false");
LogUtils.LOG.debug("failover switch is not found, " + switchFile.getName());
NAMING_LOGGER.debug("failover switch is not found, " + switchFile.getName());
return;
}
@ -123,11 +124,11 @@ public class FailoverReactor {
String line1 = line.trim();
if ("1".equals(line1)) {
switchParams.put("failover-mode", "true");
LogUtils.LOG.info("failover-mode is on");
NAMING_LOGGER.info("failover-mode is on");
new FailoverFileReader().run();
} else if ("0".equals(line1)) {
switchParams.put("failover-mode", "false");
LogUtils.LOG.info("failover-mode is off");
NAMING_LOGGER.info("failover-mode is off");
}
}
} else {
@ -136,7 +137,7 @@ public class FailoverReactor {
}
} catch (Throwable e) {
LogUtils.LOG.error("NA", "failed to read failover switch.", e);
NAMING_LOGGER.error("[NA] failed to read failover switch.", e);
}
}
}
@ -181,12 +182,12 @@ public class FailoverReactor {
try {
dom = JSON.parseObject(json, ServiceInfo.class);
} catch (Exception e) {
LogUtils.LOG.error("NA", "error while parsing cached dom : " + json, e);
NAMING_LOGGER.error("[NA] error while parsing cached dom : " + json, e);
}
}
} catch (Exception e) {
LogUtils.LOG.error("NA", "failed to read cache for dom: " + file.getName(), e);
NAMING_LOGGER.error("[NA] failed to read cache for dom: " + file.getName(), e);
} finally {
try {
if (reader != null) {
@ -201,7 +202,7 @@ public class FailoverReactor {
}
}
} catch (Exception e) {
LogUtils.LOG.error("NA", "failed to read cache file", e);
NAMING_LOGGER.error("[NA] failed to read cache file", e);
}
if (domMap.size() > 0) {

View File

@ -18,12 +18,13 @@ package com.alibaba.nacos.client.naming.beat;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import java.util.Map;
import java.util.concurrent.*;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author harold
*/
@ -31,7 +32,7 @@ public class BeatReactor {
private ScheduledExecutorService executorService;
private long clientBeatInterval = 5 * 1000;
private volatile long clientBeatInterval = 5 * 1000;
private NamingProxy serverProxy;
@ -54,17 +55,17 @@ public class BeatReactor {
}
});
executorService.scheduleAtFixedRate(new BeatProcessor(), 0, clientBeatInterval, TimeUnit.MILLISECONDS);
executorService.schedule(new BeatProcessor(), 0, TimeUnit.MILLISECONDS);
}
public void addBeatInfo(String dom, BeatInfo beatInfo) {
LogUtils.LOG.info("BEAT", "adding beat: {} to beat map.", beatInfo);
NAMING_LOGGER.info("[BEAT] adding beat: {} to beat map.", beatInfo);
dom2Beat.put(buildKey(dom, beatInfo.getIp(), beatInfo.getPort()), beatInfo);
MetricsMonitor.getDom2BeatSizeMonitor().set(dom2Beat.size());
}
public void removeBeatInfo(String dom, String ip, int port) {
LogUtils.LOG.info("BEAT", "removing beat: {}:{}:{} from beat map.", dom, ip, port);
NAMING_LOGGER.info("[BEAT] removing beat: {}:{}:{} from beat map.", dom, ip, port);
dom2Beat.remove(buildKey(dom, ip, port));
MetricsMonitor.getDom2BeatSizeMonitor().set(dom2Beat.size());
}
@ -87,7 +88,9 @@ public class BeatReactor {
executorService.schedule(new BeatTask(beatInfo), 0, TimeUnit.MILLISECONDS);
}
} catch (Exception e) {
LogUtils.LOG.error("CLIENT-BEAT", "Exception while scheduling beat.", e);
NAMING_LOGGER.error("[CLIENT-BEAT] Exception while scheduling beat.", e);
} finally {
executorService.schedule(this, clientBeatInterval, TimeUnit.MILLISECONDS);
}
}
}

View File

@ -26,8 +26,7 @@ import java.nio.channels.FileLock;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
@ -70,12 +69,12 @@ public class ConcurrentDiskUtil {
} catch (Exception e) {
++i;
if (i > RETRY_COUNT) {
log.error("NA", "read " + file.getName() + " fail;retryed time: " + i, e);
NAMING_LOGGER.error("[NA] read " + file.getName() + " fail;retryed time: " + i, e);
throw new IOException("read " + file.getAbsolutePath()
+ " conflict");
}
sleep(SLEEP_BASETIME * i);
log.warn("read " + file.getName() + " conflict;retry time: " + i);
NAMING_LOGGER.warn("read " + file.getName() + " conflict;retry time: " + i);
}
} while (null == rlock);
int fileSize = (int)fcin.size();
@ -138,12 +137,12 @@ public class ConcurrentDiskUtil {
} catch (Exception e) {
++i;
if (i > RETRY_COUNT) {
log.error("NA", "write " + file.getName() + " fail;retryed time: " + i);
NAMING_LOGGER.error("[NA] write {} fail;retryed time:{}", file.getName(), i);
throw new IOException("write " + file.getAbsolutePath()
+ " conflict", e);
}
sleep(SLEEP_BASETIME * i);
log.warn("write " + file.getName() + " conflict;retry time: " + i);
NAMING_LOGGER.warn("write " + file.getName() + " conflict;retry time: " + i);
}
} while (null == lock);
@ -161,7 +160,7 @@ public class ConcurrentDiskUtil {
lock.release();
lock = null;
} catch (IOException e) {
log.warn("close wrong", e);
NAMING_LOGGER.warn("close wrong", e);
}
}
if (channel != null) {
@ -169,7 +168,7 @@ public class ConcurrentDiskUtil {
channel.close();
channel = null;
} catch (IOException e) {
log.warn("close wrong", e);
NAMING_LOGGER.warn("close wrong", e);
}
}
if (raf != null) {
@ -177,7 +176,7 @@ public class ConcurrentDiskUtil {
raf.close();
raf = null;
} catch (IOException e) {
log.warn("close wrong", e);
NAMING_LOGGER.warn("close wrong", e);
}
}
@ -208,11 +207,10 @@ public class ConcurrentDiskUtil {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
log.warn("sleep wrong", e);
NAMING_LOGGER.warn("sleep wrong", e);
}
}
static final public Logger log = LogUtils.LOG;
static final int RETRY_COUNT = 10;
static final int SLEEP_BASETIME = 10;
}

View File

@ -19,7 +19,6 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.StringUtils;
import java.io.BufferedReader;
@ -32,6 +31,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author xuanyin
*/
@ -66,7 +67,7 @@ public class DiskCache {
ConcurrentDiskUtil.writeFileContent(file, keyContentBuffer.toString(), Charset.defaultCharset().toString());
} catch (Throwable e) {
LogUtils.LOG.error("NA", "failed to write cache for dom:" + dom.getName(), e);
NAMING_LOGGER.error("[NA] failed to write cache for dom:" + dom.getName(), e);
}
}
@ -118,11 +119,11 @@ public class DiskCache {
ips.add(JSON.parseObject(json, Instance.class));
}
} catch (Throwable e) {
LogUtils.LOG.error("NA", "error while parsing cache file: " + json, e);
NAMING_LOGGER.error("[NA] error while parsing cache file: " + json, e);
}
}
} catch (Exception e) {
LogUtils.LOG.error("NA", "failed to read cache for dom: " + file.getName(), e);
NAMING_LOGGER.error("[NA] failed to read cache for dom: " + file.getName(), e);
} finally {
try {
if (reader != null) {
@ -142,7 +143,7 @@ public class DiskCache {
}
} catch (Throwable e) {
LogUtils.LOG.error("NA", "failed to read cache file", e);
NAMING_LOGGER.error("[NA] failed to read cache file", e);
}
return domMap;

View File

@ -19,13 +19,14 @@ import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.utils.Chooser;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author xuanyin
*/
@ -71,15 +72,15 @@ public class Balancer {
* @return The random-weight result of the host
*/
protected static Instance getHostByRandomWeight(List<Instance> hosts) {
LogUtils.LOG.debug("entry randomWithWeight");
NAMING_LOGGER.debug("entry randomWithWeight");
if (hosts == null || hosts.size() == 0) {
LogUtils.LOG.debug("hosts == null || hosts.size() == 0");
NAMING_LOGGER.debug("hosts == null || hosts.size() == 0");
return null;
}
Chooser<String, Instance> vipChooser = new Chooser<String, Instance>("www.taobao.com");
LogUtils.LOG.debug("new Chooser");
NAMING_LOGGER.debug("new Chooser");
List<Pair<Instance>> hostsWithWeight = new ArrayList<Pair<Instance>>();
for (Instance host : hosts) {
@ -87,9 +88,9 @@ public class Balancer {
hostsWithWeight.add(new Pair<Instance>(host, host.getWeight()));
}
}
LogUtils.LOG.debug("for (Host host : hosts)");
NAMING_LOGGER.debug("for (Host host : hosts)");
vipChooser.refresh(hostsWithWeight);
LogUtils.LOG.debug("vipChooser.refresh");
NAMING_LOGGER.debug("vipChooser.refresh");
Instance host = vipChooser.randomWithWeight();
return host;
}

View File

@ -20,7 +20,6 @@ import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import java.util.ArrayList;
import java.util.Collections;
@ -28,6 +27,8 @@ import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author xuanyin
*/
@ -57,7 +58,7 @@ public class EventDispatcher {
public void addListener(ServiceInfo serviceInfo, String clusters, EventListener listener) {
LogUtils.LOG.info("LISTENER", "adding " + serviceInfo.getName() + " with " + clusters + " to listener map");
NAMING_LOGGER.info("[LISTENER] adding " + serviceInfo.getName() + " with " + clusters + " to listener map");
List<EventListener> observers = Collections.synchronizedList(new ArrayList<EventListener>());
observers.add(listener);
@ -71,7 +72,7 @@ public class EventDispatcher {
public void removeListener(String serviceName, String clusters, EventListener listener) {
LogUtils.LOG.info("LISTENER", "removing " + serviceName + " with " + clusters + " from listener map");
NAMING_LOGGER.info("[LISTENER] removing " + serviceName + " with " + clusters + " from listener map");
List<EventListener> observers = observerMap.get(ServiceInfo.getKey(serviceName, clusters));
if (observers != null) {
@ -129,7 +130,7 @@ public class EventDispatcher {
}
} catch (Exception e) {
LogUtils.LOG.error("NA", "notify error for service: "
NAMING_LOGGER.error("[NA] notify error for service: "
+ serviceInfo.getName() + ", clusters: " + serviceInfo.getClusters(), e);
}
}

View File

@ -23,7 +23,6 @@ import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.naming.backups.FailoverReactor;
import com.alibaba.nacos.client.naming.cache.DiskCache;
import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@ -31,6 +30,8 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.*;
import java.util.concurrent.*;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author xuanyin
*/
@ -107,7 +108,7 @@ public class HostReactor {
if (oldService != null) {
if (oldService.getLastRefTime() > serviceInfo.getLastRefTime()) {
LogUtils.LOG.warn("out of date data received, old-t: " + oldService.getLastRefTime()
NAMING_LOGGER.warn("out of date data received, old-t: " + oldService.getLastRefTime()
+ ", new-t: " + serviceInfo.getLastRefTime());
}
@ -160,17 +161,17 @@ public class HostReactor {
}
if (newHosts.size() > 0) {
LogUtils.LOG.info("new ips(" + newHosts.size() + ") service: "
NAMING_LOGGER.info("new ips(" + newHosts.size() + ") service: "
+ serviceInfo.getName() + " -> " + JSON.toJSONString(newHosts));
}
if (remvHosts.size() > 0) {
LogUtils.LOG.info("removed ips(" + remvHosts.size() + ") service: "
NAMING_LOGGER.info("removed ips(" + remvHosts.size() + ") service: "
+ serviceInfo.getName() + " -> " + JSON.toJSONString(remvHosts));
}
if (modHosts.size() > 0) {
LogUtils.LOG.info("modified ips(" + modHosts.size() + ") service: "
NAMING_LOGGER.info("modified ips(" + modHosts.size() + ") service: "
+ serviceInfo.getName() + " -> " + JSON.toJSONString(modHosts));
}
@ -182,7 +183,7 @@ public class HostReactor {
}
} else {
LogUtils.LOG.info("new ips(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getName() + " -> " + JSON
NAMING_LOGGER.info("new ips(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getName() + " -> " + JSON
.toJSONString(serviceInfo.getHosts()));
serviceInfoMap.put(serviceInfo.getKey(), serviceInfo);
eventDispatcher.serviceChanged(serviceInfo);
@ -192,7 +193,7 @@ public class HostReactor {
MetricsMonitor.getServiceInfoMapSizeMonitor().set(serviceInfoMap.size());
LogUtils.LOG.info("current ips:(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getName() +
NAMING_LOGGER.info("current ips:(" + serviceInfo.ipCount() + ") service: " + serviceInfo.getName() +
" -> " + JSON.toJSONString(serviceInfo.getHosts()));
return serviceInfo;
@ -215,7 +216,7 @@ public class HostReactor {
public ServiceInfo getServiceInfo(final String serviceName, final String clusters) {
LogUtils.LOG.debug("failover-mode: " + failoverReactor.isFailoverSwitch());
NAMING_LOGGER.debug("failover-mode: " + failoverReactor.isFailoverSwitch());
String key = ServiceInfo.getKey(serviceName, clusters);
if (failoverReactor.isFailoverSwitch()) {
return failoverReactor.getService(key);
@ -240,8 +241,7 @@ public class HostReactor {
try {
serviceObj.wait(updateHoldInterval);
} catch (InterruptedException e) {
LogUtils.LOG.error("[getServiceInfo]",
"serviceName:" + serviceName + ", clusters:" + clusters, e);
NAMING_LOGGER.error("[getServiceInfo] serviceName:" + serviceName + ", clusters:" + clusters, e);
}
}
}
@ -277,7 +277,7 @@ public class HostReactor {
processServiceJSON(result);
}
} catch (Exception e) {
LogUtils.LOG.error("NA", "failed to update serviceName: " + serviceName, e);
NAMING_LOGGER.error("[NA] failed to update serviceName: " + serviceName, e);
} finally {
if (oldService != null) {
synchronized (oldService) {
@ -291,7 +291,7 @@ public class HostReactor {
try {
serverProxy.queryList(serviceName, clusters, pushReceiver.getUDPPort(), false);
} catch (Exception e) {
LogUtils.LOG.error("NA", "failed to update serviceName: " + serviceName, e);
NAMING_LOGGER.error("[NA] failed to update serviceName: " + serviceName, e);
}
}
@ -329,7 +329,7 @@ public class HostReactor {
lastRefTime = serviceObj.getLastRefTime();
} catch (Throwable e) {
LogUtils.LOG.warn("NA", "failed to update serviceName: " + serviceName, e);
NAMING_LOGGER.warn("[NA] failed to update serviceName: " + serviceName, e);
}
}

View File

@ -17,7 +17,6 @@ package com.alibaba.nacos.client.naming.core;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.naming.utils.IoUtils;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.StringUtils;
import java.net.DatagramPacket;
@ -27,6 +26,8 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author xuanyin
*/
@ -57,7 +58,7 @@ public class PushReceiver implements Runnable {
executorService.execute(this);
} catch (Exception e) {
LogUtils.LOG.error("NA", "init udp socket failed", e);
NAMING_LOGGER.error("[NA] init udp socket failed", e);
}
}
@ -72,7 +73,7 @@ public class PushReceiver implements Runnable {
udpSocket.receive(packet);
String json = new String(IoUtils.tryDecompress(packet.getData()), "UTF-8").trim();
LogUtils.LOG.info("received push data: " + json + " from " + packet.getAddress().toString());
NAMING_LOGGER.info("received push data: " + json + " from " + packet.getAddress().toString());
PushPacket pushPacket = JSON.parseObject(json, PushPacket.class);
String ack;
@ -100,7 +101,7 @@ public class PushReceiver implements Runnable {
udpSocket.send(new DatagramPacket(ack.getBytes(Charset.forName("UTF-8")),
ack.getBytes(Charset.forName("UTF-8")).length, packet.getSocketAddress()));
} catch (Exception e) {
LogUtils.LOG.error("NA", "error while receiving push data", e);
NAMING_LOGGER.error("[NA] error while receiving push data", e);
}
}
}

View File

@ -16,7 +16,6 @@
package com.alibaba.nacos.client.naming.net;
import com.alibaba.nacos.client.naming.utils.IoUtils;
import com.alibaba.nacos.client.naming.utils.LogUtils;
import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.google.common.net.HttpHeaders;
@ -30,6 +29,8 @@ import java.net.URLEncoder;
import java.util.*;
import java.util.zip.GZIPInputStream;
import static com.alibaba.nacos.client.utils.LogUtils.*;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
@ -70,20 +71,20 @@ public class HttpClient {
conn.setRequestMethod(method);
setHeaders(conn, headers, encoding);
conn.connect();
LogUtils.LOG.debug("Request from server: " + url);
NAMING_LOGGER.debug("Request from server: " + url);
return getResult(conn);
} catch (Exception e) {
try {
if (conn != null) {
LogUtils.LOG.warn("failed to request " + conn.getURL() + " from "
NAMING_LOGGER.warn("failed to request " + conn.getURL() + " from "
+ InetAddress.getByName(conn.getURL().getHost()).getHostAddress());
}
} catch (Exception e1) {
LogUtils.LOG.error("NA", "failed to request ", e1);
NAMING_LOGGER.error("[NA] failed to request ", e1);
//ignore
}
LogUtils.LOG.error("NA", "failed to request ", e);
NAMING_LOGGER.error("[NA] failed to request ", e);
return new HttpResult(500, e.toString(), Collections.<String, String>emptyMap());
} finally {

View File

@ -27,19 +27,30 @@ import com.alibaba.nacos.api.selector.ExpressionSelector;
import com.alibaba.nacos.api.selector.SelectorType;
import com.alibaba.nacos.client.monitor.MetricsMonitor;
import com.alibaba.nacos.client.naming.beat.BeatInfo;
import com.alibaba.nacos.client.naming.utils.*;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.client.naming.utils.IoUtils;
import com.alibaba.nacos.client.naming.utils.NetUtils;
import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import com.alibaba.nacos.common.util.HttpMethod;
import com.alibaba.nacos.common.util.UuidUtils;
import java.io.IOException;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
@ -131,7 +142,7 @@ public class NamingProxy {
try {
if (!CollectionUtils.isEmpty(serverList)) {
LogUtils.LOG.debug("server list provided by user: " + serverList);
NAMING_LOGGER.debug("server list provided by user: " + serverList);
return;
}
@ -146,19 +157,19 @@ public class NamingProxy {
}
if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) {
LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list);
NAMING_LOGGER.info("[SERVER-LIST] server list is updated: " + list);
}
serversFromEndpoint = list;
lastSrvRefTime = System.currentTimeMillis();
} catch (Throwable e) {
LogUtils.LOG.warn("failed to update server list", e);
NAMING_LOGGER.warn("failed to update server list", e);
}
}
public void registerService(String serviceName, Instance instance) throws NacosException {
LogUtils.LOG.info("REGISTER-SERVICE", "{} registering service {} with instance: {}",
NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}",
namespaceId, serviceName, instance);
final Map<String, String> params = new HashMap<String, String>(8);
@ -178,7 +189,7 @@ public class NamingProxy {
public void deregisterService(String serviceName, String ip, int port, String cluster) throws NacosException {
LogUtils.LOG.info("DEREGISTER-SERVICE", "{} deregistering service {} with instance: {}:{}@{}",
NAMING_LOGGER.info("[DEREGISTER-SERVICE] {} deregistering service {} with instance: {}:{}@{}",
namespaceId, serviceName, ip, port, cluster);
final Map<String, String> params = new HashMap<String, String>(8);
@ -191,7 +202,8 @@ public class NamingProxy {
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE);
}
public String queryList(String serviceName, String clusters, int udpPort, boolean healthyOnly) throws NacosException {
public String queryList(String serviceName, String clusters, int udpPort, boolean healthyOnly)
throws NacosException {
final Map<String, String> params = new HashMap<String, String>(8);
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
@ -206,7 +218,7 @@ public class NamingProxy {
public long sendBeat(BeatInfo beatInfo) {
try {
LogUtils.LOG.info("BEAT", "{} sending beat to server: {}", namespaceId, beatInfo.toString());
NAMING_LOGGER.info("[BEAT] {} sending beat to server: {}", namespaceId, beatInfo.toString());
Map<String, String> params = new HashMap<String, String>(4);
params.put("beat", JSON.toJSONString(beatInfo));
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
@ -218,7 +230,7 @@ public class NamingProxy {
return jsonObject.getLong("clientBeatInterval");
}
} catch (Exception e) {
LogUtils.LOG.error("CLIENT-BEAT", "failed to send beat: " + JSON.toJSONString(beatInfo), e);
NAMING_LOGGER.error("[CLIENT-BEAT] failed to send beat: " + JSON.toJSONString(beatInfo), e);
}
return 0L;
}
@ -250,7 +262,7 @@ public class NamingProxy {
case none:
break;
case label:
ExpressionSelector expressionSelector = (ExpressionSelector) selector;
ExpressionSelector expressionSelector = (ExpressionSelector)selector;
params.put("selector", JSON.toJSONString(expressionSelector));
break;
default:
@ -271,7 +283,6 @@ public class NamingProxy {
public String reqAPI(String api, Map<String, String> params) throws NacosException {
List<String> snapshot = serversFromEndpoint;
if (!CollectionUtils.isEmpty(serverList)) {
snapshot = serverList;
@ -316,7 +327,7 @@ public class NamingProxy {
end = System.currentTimeMillis();
MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code))
.record(end - start, TimeUnit.MILLISECONDS);
.observe(end - start);
if (HttpURLConnection.HTTP_OK == result.code) {
return result.content;
@ -326,7 +337,7 @@ public class NamingProxy {
return StringUtils.EMPTY;
}
LogUtils.LOG.error("CALL-SERVER", "failed to req API:" + HttpClient.getPrefix() + curServer
NAMING_LOGGER.error("[CALL-SERVER] failed to req API:" + HttpClient.getPrefix() + curServer
+ api + ". code:"
+ result.code + " msg: " + result.content);
@ -357,7 +368,7 @@ public class NamingProxy {
try {
return callServer(api, params, server, method);
} catch (Exception e) {
LogUtils.LOG.error("NA", "req api:" + api + " failed, server(" + server, e);
NAMING_LOGGER.error("[NA] req api:" + api + " failed, server(" + server, e);
}
index = (index + 1) % servers.size();
@ -370,7 +381,7 @@ public class NamingProxy {
try {
return callServer(api, params, nacosDomain);
} catch (Exception e) {
LogUtils.LOG.error("NA", "req api:" + api + " failed, server(" + nacosDomain, e);
NAMING_LOGGER.error("[NA] req api:" + api + " failed, server(" + nacosDomain, e);
}
}
@ -382,3 +393,4 @@ public class NamingProxy {
return namespaceId;
}
}

View File

@ -1,58 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.naming.utils;
import com.alibaba.nacos.client.logger.Level;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.LoggerFactory;
/**
* @author dingjoey
*/
public class LogUtils {
static int JM_LOG_RETAIN_COUNT = 7;
static String JM_LOG_FILE_SIZE = "10MB";
public static final Logger LOG;
static {
String tmp = "7";
try {
tmp = System.getProperty("JM.LOG.RETAIN.COUNT", "7");
JM_LOG_RETAIN_COUNT = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
e.printStackTrace();
throw e;
}
JM_LOG_FILE_SIZE = System.getProperty("JM.LOG.FILE.SIZE", "10MB");
// logger init
LOG = LoggerFactory.getLogger("com.alibaba.nacos.client.naming");
LOG.setLevel(Level.DEBUG);
LOG.setAdditivity(false);
LOG.activateAppenderWithSizeRolling("nacos", "naming.log", "UTF-8", JM_LOG_FILE_SIZE, JM_LOG_RETAIN_COUNT);
}
public static Logger logger(Class<?> clazz) {
return LoggerFactory.getLogger(clazz);
}
public static void setLogLevel(String level) {
LOG.setLevel(Level.codeOf(level.toUpperCase()));
}
}

View File

@ -15,12 +15,11 @@
*/
package com.alibaba.nacos.client.utils;
import org.slf4j.Logger;
import java.util.List;
import java.util.Map;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.logger.Logger;
/**
* env util.
*
@ -28,7 +27,7 @@ import com.alibaba.nacos.client.logger.Logger;
*/
public class EnvUtil {
final static public Logger log = LogUtils.logger(EnvUtil.class);
final static public Logger LOGGER = LogUtils.logger(EnvUtil.class);
public static void setSelfEnv(Map<String, List<String>> headers) {
if (headers != null) {
@ -36,13 +35,13 @@ public class EnvUtil {
if (amorayTagTmp == null) {
if (selfAmorayTag != null) {
selfAmorayTag = null;
log.warn("selfAmoryTag:null");
LOGGER.warn("selfAmoryTag:null");
}
} else {
String amorayTagTmpStr = listToString(amorayTagTmp);
if (!amorayTagTmpStr.equals(selfAmorayTag)) {
selfAmorayTag = amorayTagTmpStr;
log.warn("selfAmoryTag:{}", selfAmorayTag);
LOGGER.warn("selfAmoryTag:{}", selfAmorayTag);
}
}
@ -50,26 +49,26 @@ public class EnvUtil {
if (vipserverTagTmp == null) {
if (selfVipserverTag != null) {
selfVipserverTag = null;
log.warn("selfVipserverTag:null");
LOGGER.warn("selfVipserverTag:null");
}
} else {
String vipserverTagTmpStr = listToString(vipserverTagTmp);
if (!vipserverTagTmpStr.equals(selfVipserverTag)) {
selfVipserverTag = vipserverTagTmpStr;
log.warn("selfVipserverTag:{}", selfVipserverTag);
LOGGER.warn("selfVipserverTag:{}", selfVipserverTag);
}
}
List<String> locationTagTmp = headers.get(LOCATION_TAG);
if (locationTagTmp == null) {
if (selfLocationTag != null) {
selfLocationTag = null;
log.warn("selfLocationTag:null");
LOGGER.warn("selfLocationTag:null");
}
} else {
String locationTagTmpStr = listToString(locationTagTmp);
if (!locationTagTmpStr.equals(selfLocationTag)) {
selfLocationTag = locationTagTmpStr;
log.warn("selfLocationTag:{}", selfLocationTag);
LOGGER.warn("selfLocationTag:{}", selfLocationTag);
}
}
}

View File

@ -0,0 +1,68 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.client.logging.AbstractNacosLogging;
import com.alibaba.nacos.client.logging.log4j2.Log4J2NacosLogging;
import com.alibaba.nacos.client.logging.logback.LogbackNacosLogging;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
* @author <a href="mailto:huangxiaoyu1018@gmail.com">hxy1991</a>
* @since 0.9.0
*/
public class LogUtils {
public static final Logger NAMING_LOGGER;
static {
try {
boolean isLogback = false;
AbstractNacosLogging nacosLogging;
try {
Class.forName("ch.qos.logback.classic.Logger");
nacosLogging = new LogbackNacosLogging();
isLogback = true;
} catch (ClassNotFoundException e) {
nacosLogging = new Log4J2NacosLogging();
}
try {
nacosLogging.loadConfiguration();
} catch (Throwable t) {
if (isLogback) {
getLogger(LogUtils.class).warn("Load Logback Configuration of Nacos fail, message: {}",
t.getMessage());
} else {
getLogger(LogUtils.class).warn("Load Log4j Configuration of Nacos fail, message: {}",
t.getMessage());
}
}
} catch (Throwable t1) {
getLogger(LogUtils.class).warn("Init Nacos Logging fail, message: {}", t1.getMessage());
}
NAMING_LOGGER = getLogger("com.alibaba.nacos.client.naming");
}
public static Logger logger(Class<?> clazz) {
return getLogger(clazz);
}
}

View File

@ -15,21 +15,19 @@
*/
package com.alibaba.nacos.client.utils;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient;
import org.slf4j.Logger;
import java.io.InputStream;
import java.util.Properties;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.config.utils.ParamUtils;
import com.alibaba.nacos.client.logger.Logger;
/**
* manage param tool
*
* @author nacos
*/
public class ParamUtil {
final static public Logger log = LogUtils.logger(ParamUtils.class);
private final static Logger LOGGER = LogUtils.logger(ParamUtil.class);
private static String defaultContextPath = "nacos";
private static String defaultNodesPath = "serverlist";
@ -49,7 +47,7 @@ public class ParamUtil {
String defaultServerPortTmp = "8848";
defaultServerPort = System.getProperty("nacos.server.port", defaultServerPortTmp);
log.info("settings", "[req-serv] nacos-server port:{}", defaultServerPort);
LOGGER.info("[settings] [req-serv] nacos-server port:{}", defaultServerPort);
String tmp = "1000";
try {
@ -57,10 +55,10 @@ public class ParamUtil {
connectTimeout = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
final String msg = "[http-client] invalid connect timeout:" + tmp;
log.error("settings", "NACOS-XXXX", msg, e);
LOGGER.error("[settings] " + msg, e);
throw new IllegalArgumentException(msg, e);
}
log.info("settings", "[http-client] connect timeout:{}", connectTimeout);
LOGGER.info("[settings] [http-client] connect timeout:{}", connectTimeout);
try {
InputStream in = HttpSimpleClient.class.getClassLoader()
@ -72,16 +70,16 @@ public class ParamUtil {
if (val != null) {
clientVersion = val;
}
log.info("NACOS_CLIENT_VERSION:{}", clientVersion);
LOGGER.info("NACOS_CLIENT_VERSION: {}", clientVersion);
} catch (Exception e) {
log.error("500", "read application.properties", e);
LOGGER.error("[500] read application.properties", e);
}
try {
perTaskConfigSize = Double.valueOf(System.getProperty("PER_TASK_CONFIG_SIZE", "3000"));
log.warn("PER_TASK_CONFIG_SIZE:", perTaskConfigSize);
LOGGER.info("PER_TASK_CONFIG_SIZE: {}", perTaskConfigSize);
} catch (Throwable t) {
log.error("PER_TASK_CONFIG_SIZE", "PER_TASK_CONFIG_SIZE invalid", t);
LOGGER.error("[PER_TASK_CONFIG_SIZE] PER_TASK_CONFIG_SIZE invalid", t);
}
}

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<RollingFile name="CONFIG_LOG_FILE" fileName="${sys:user.home}/logs/nacos/config.log"
filePattern="${sys:user.home}/logs/nacos/config.log.%d{yyyy-MM-dd}.%i">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="${sys:JM.LOG.FILE.SIZE:-10MB}"/>
</Policies>
<DefaultRolloverStrategy max="${sys:JM.LOG.RETAIN.COUNT:-7}"/>
</RollingFile>
<RollingFile name="NAMING_LOG_FILE" fileName="${sys:user.home}/logs/nacos/naming.log"
filePattern="${sys:user.home}/logs/nacos/naming.log.%d{yyyy-MM-dd}.%i">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="${sys:JM.LOG.FILE.SIZE:-10MB}"/>
</Policies>
<DefaultRolloverStrategy max="${sys:JM.LOG.RETAIN.COUNT:-7}"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.alibaba.nacos.client" level="${sys:com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<AppenderRef ref="CONFIG_LOG_FILE"/>
</Logger>
<Logger name="com.alibaba.nacos.client.config" level="${sys:com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<AppenderRef ref="CONFIG_LOG_FILE"/>
</Logger>
<Logger name="com.alibaba.nacos.client.naming" level="${sys:com.alibaba.nacos.naming.log.level:-info}"
additivity="false">
<AppenderRef ref="NAMING_LOG_FILE"/>
</Logger>
</Loggers>
</Configuration>

View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="30 seconds" packagingData="true">
<contextName>nacos</contextName>
<appender name="CONFIG_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${user.home}/logs/nacos/config.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${user.home}/logs/nacos/config.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxHistory>${JM.LOG.RETAIN.COUNT:-7}</maxHistory>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>${JM.LOG.FILE.SIZE:-10MB}</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</pattern>
</encoder>
</appender>
<appender name="NAMING_LOG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${user.home}/logs/nacos/naming.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${user.home}/logs/nacos/naming.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<maxHistory>${JM.LOG.RETAIN.COUNT:-7}</maxHistory>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>${JM.LOG.FILE.SIZE:-10MB}</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%-5t:%c{2}] %m%n</pattern>
</encoder>
</appender>
<logger name="com.alibaba.nacos.client" level="${com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<appender-ref ref="CONFIG_LOG_FILE"/>
</logger>
<logger name="com.alibaba.nacos.client.config" level="${com.alibaba.nacos.config.log.level:-info}"
additivity="false">
<appender-ref ref="CONFIG_LOG_FILE"/>
</logger>
<logger name="com.alibaba.nacos.client.naming" level="${com.alibaba.nacos.naming.log.level:-info}"
additivity="false">
<appender-ref ref="NAMING_LOG_FILE"/>
</logger>
</configuration>

View File

@ -18,7 +18,7 @@
<parent>
<artifactId>nacos-all</artifactId>
<groupId>com.alibaba.nacos</groupId>
<version>0.8.0</version>
<version>0.9.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -18,7 +18,7 @@
<parent>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId>
<version>0.8.0</version>
<version>0.9.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -57,4 +57,16 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>6</source>
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,60 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.common.util;
/**
* @author <a href="mailto:huangxiaoyu1018@gmail.com">hxy1991</a>
* @since 0.9.0
*/
public class ClassUtils {
public static ClassLoader getDefaultClassLoader() {
try {
return Thread.currentThread().getContextClassLoader();
} catch (Throwable t) {
// ignore
}
ClassLoader classLoader = ClassUtils.class.getClassLoader();
if (classLoader != null) {
return classLoader;
}
try {
return ClassLoader.getSystemClassLoader();
} catch (Throwable t) {
// ignore
}
return null;
}
public static boolean isPresent(String className) {
ClassLoader defaultClassLoader = getDefaultClassLoader();
try {
if (defaultClassLoader != null) {
defaultClassLoader.loadClass(className);
} else {
Class.forName(className);
}
return true;
} catch (Throwable t) {
return false;
}
}
}

View File

@ -1,30 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.common.util;
/**
* Nacos common constants
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 0.2.2
*/
public interface Constants {
/**
* Spring Profile : "standalone"
*/
String STANDALONE_SPRING_PROFILE = "standalone";
}

View File

@ -13,11 +13,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.utils;
package com.alibaba.nacos.common.util;
import com.alibaba.nacos.config.server.constant.Constants;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
@ -29,6 +33,8 @@ import java.util.Properties;
*/
public class ResourceUtils {
private static final String CLASSPATH_PREFIX = "classpath:";
/**
* Returns the URL of the resource on the classpath
*
@ -37,8 +43,24 @@ public class ResourceUtils {
* @throws IOException If the resource cannot be found or read
*/
public static URL getResourceURL(String resource) throws IOException {
ClassLoader loader = ResourceUtils.class.getClassLoader();
return getResourceURL(loader, resource);
if (resource.startsWith(CLASSPATH_PREFIX)) {
String path = resource.substring(CLASSPATH_PREFIX.length());
ClassLoader classLoader = ResourceUtils.class.getClassLoader();
URL url = (classLoader != null ? classLoader.getResource(path) : ClassLoader.getSystemResource(path));
if (url == null) {
throw new FileNotFoundException("Resource [" + resource + "] does not exist");
}
return url;
}
try {
return new URL(resource);
} catch (MalformedURLException ex) {
return new File(resource).toURI().toURL();
}
}
/**
@ -119,9 +141,7 @@ public class ResourceUtils {
*/
public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
InputStream in = getResourceAsStream(loader, resource);
props.load(in);
in.close();
return props;
@ -134,8 +154,8 @@ public class ResourceUtils {
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static InputStreamReader getResourceAsReader(String resource) throws IOException {
return new InputStreamReader(getResourceAsStream(resource), Constants.ENCODE);
public static InputStreamReader getResourceAsReader(String resource, String charsetName) throws IOException {
return new InputStreamReader(getResourceAsStream(resource), charsetName);
}
/**
@ -146,8 +166,9 @@ public class ResourceUtils {
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
return new InputStreamReader(getResourceAsStream(loader, resource), Constants.ENCODE);
public static Reader getResourceAsReader(ClassLoader loader, String resource, String charsetName)
throws IOException {
return new InputStreamReader(getResourceAsStream(loader, resource), charsetName);
}
/**
@ -161,6 +182,16 @@ public class ResourceUtils {
return new File(getResourceURL(resource).getFile());
}
/**
* Returns a resource on the classpath as a File object
*
* @param url The resource url to find
* @return The resource
*/
public static File getResourceAsFile(URL url) {
return new File(url.getFile());
}
/**
* Returns a resource on the classpath as a File object
*

View File

@ -0,0 +1,46 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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.
*/
package com.alibaba.nacos.common.util;
import java.io.InputStream;
import java.util.Properties;
/**
* @author xingxuechao
* on:2019/2/27 12:32 PM
*/
public class VersionUtils {
public static String VERSION;
/**获取当前version*/
public static final String VERSION_DEFAULT = "${project.version}";
static{
try{
InputStream in = VersionUtils.class.getClassLoader()
.getResourceAsStream("nacos-version.txt");
Properties props = new Properties();
props.load(in);
String val = props.getProperty("version");
if (val != null && !VERSION_DEFAULT.equals(val)) {
VERSION = val;
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

View File

@ -17,7 +17,7 @@
<parent>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId>
<version>0.8.0</version>
<version>0.9.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -44,7 +44,7 @@ import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import static com.alibaba.nacos.common.util.SystemUtils.LOCAL_IP;
import static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;
/**
* 软负载客户端发布数据专用控制器

View File

@ -41,7 +41,7 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
/**

View File

@ -27,7 +27,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.PostConstruct;
import static com.alibaba.nacos.common.util.SystemUtils.LOCAL_IP;
import static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;
/**
* health service

View File

@ -15,7 +15,7 @@
*/
package com.alibaba.nacos.config.server.model.app;
import static com.alibaba.nacos.common.util.SystemUtils.LOCAL_IP;
import static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;
/**
* app info

View File

@ -40,7 +40,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.service.PersistService.CONFIG_INFO4BETA_ROW_MAPPER;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;

View File

@ -33,7 +33,7 @@ import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.utils.LogUtil.*;
/**

View File

@ -29,7 +29,7 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import static com.alibaba.nacos.common.util.SystemUtils.NACOS_HOME;
import static com.alibaba.nacos.core.utils.SystemUtils.NACOS_HOME;
/**
* 磁盘操作工具类

View File

@ -21,7 +21,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
/**
* datasource adapter

View File

@ -40,9 +40,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.common.util.SystemUtils.NACOS_HOME;
import static com.alibaba.nacos.common.util.SystemUtils.NACOS_HOME_KEY;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.core.utils.SystemUtils.NACOS_HOME;
import static com.alibaba.nacos.core.utils.SystemUtils.NACOS_HOME_KEY;
import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
/**
* local data source

View File

@ -48,9 +48,9 @@ import java.util.*;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.common.util.SystemUtils.LOCAL_IP;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.common.util.SystemUtils.readClusterConf;
import static com.alibaba.nacos.core.utils.SystemUtils.LOCAL_IP;
import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.core.utils.SystemUtils.readClusterConf;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;

View File

@ -35,7 +35,7 @@ import javax.annotation.PostConstruct;
import java.sql.*;
import java.util.List;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
/**

Some files were not shown because too many files have changed in this diff Show More