前几篇文章可以参考:
今天说说代码篇。
1、安装ES
docker run --name elasticsearch \
-p 9200:9200 -p 9300:9300 \
-e "discovery.type=single-node" \
-e ES_JAVA_OPTS="-Xms512m -Xmx512m" \
-d elasticsearch:6.8.19
2、安装Kibana
docker run -d --name kibana \
-p 5601:5601 \
-v D:/Code/k8s/kibana/kibana.yml:/usr/share/kibana/config/kibana.yml kibana:6.8.0
docker run -p 11800:11800 -d \
-e SW_NAMESPACE=bg\
-e SW_STORAGE=elasticsearch \
-e SW_STORAGE_ES_CLUSTER_NODES=xxxxxx \
-e SW_ES_USER=xxx \
-e SW_ES_PASSWORD=xxx \
apache/skywalking-oap-server:8.9.0
docker run -p 12800:12800 -d \
-e SW_NAMESPACE=bg \
-e SW_STORAGE=elasticsearch \
-e SW_STORAGE_ES_CLUSTER_NODES=xxxxx \
-e SW_ES_USER=xxx \
-e SW_ES_PASSWORD=xxx \
-e SW_SEARCHABLE_TAG_KEYS=http.method,status_code,db.type,db.instance,mq.queue,mq.topic,mq.broker,input,output,userId,account,number,systemid \
apache/skywalking-oap-server:8.9.0
docker run -p 8080:8080 -d \
-e SW_OAP_ADDRESS=http://xxxx:12800 \
apache/skywalking-ui:8.9.0
以上环境变量均可配置到k8s中。
<PackageReference Include="SkyAPM.Agent.AspNetCore" Version="1.3.0" />
说明
ps:skyapm.json需要设置属性——始终复制
{
"SkyWalking": {
"ServiceName": "bg::op::gateway",
"Namespace": "",
"HeaderVersions": [
"sw8"
],
"Sampling": {
"SamplePer3Secs": -1,
"Percentage": -1.0,
"IgnorePaths": ["**/nacos/**"]
},
"Logging": {
"Level": "Debug",
"FilePath": "logs/skyapm-{Date}.log"
},
"Transport": {
"Interval": 3000,
"ProtocolVersion": "v8",
"QueueSize": 30000,
"BatchSize": 3000,
"gRPC": {
"Servers": "bg-oap:11800",
"Timeout": 10000,
"ConnectTimeout": 10000,
"ReportTimeout": 600000
}
}
}
}
ASPNETCORE_HOSTINGSTARTUPASSEMBLIES = SkyAPM.Agent.AspNetCore
在容器内,会生成skyapm-2022xxxx.log文件,会有详细的连接信息和推送信息。 同时要检查下是否包含skyapm.json文件。
FROM apache/skywalking-java-agent:8.8.0-java11 AS bg-base
WORKDIR /app
// ...
COPY --from=bg-base /skywalking/agent/optional-plugins/apm-trace-ignore-plugin-8.8.0.jar /skywalking/agent/plugins/apm-trace-ignore-plugin-8.8.0.jar
ENTRYPOINT ["sh","-c","exec java -Xmx1024m -Xms1024m -Dproject.name=app-bg -Dskywalking.trace.ignore_path='**/nacos/**,**/JDBI/**' -Duser.language=zh -Duser.country=CN -jar /app/app.jar"]
SW_AGENT_COLLECTOR_BACKEND_SERVICES=bg-oap:11800
SW_AGENT_NAME="bg::op::svc"
1、添加依赖包
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>apm-toolkit-trace</artifactId>
<version>8.7.0</version>
<scope>provided</scope>
</dependency>
2、设计过滤器
@Slf4j
@Component
public class ApmHttpInfoFilter extends HttpFilter {
private static final ImmutableSet<String> IGNORED_HEADERS;
static {
Set<String> ignoredHeaders = ImmutableSet.of(
"Content-Type",
"User-Agent",
"Accept",
"Cache-Control",
"Postman-Token",
"Host",
"Accept-Encoding",
"Connection",
"Content-Length")
.stream()
.map(String::toUpperCase)
.collect(Collectors.toSet());
IGNORED_HEADERS = ImmutableSet.copyOf(ignoredHeaders);
}
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
try {
filterChain.doFilter(requestWrapper, responseWrapper);
} finally {
try {
//构造请求信息: 比如 curl -X GET http://localhost:18080/getPerson?id=1 -H 'token: me-token' -d '{ "name": "hello" }'
//构造请求的方法&URL&参数
StringBuilder sb = new StringBuilder("curl")
.append(" -X ").append(request.getMethod())
.append(" ").append(request.getRequestURL().toString());
if (StringUtils.hasLength(request.getQueryString())) {
sb.append("?").append(request.getQueryString());
}
//构造header
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if (!IGNORED_HEADERS.contains(headerName.toUpperCase())) {
sb.append(" -H '").append(headerName).append(": ").append(request.getHeader(headerName)).append("'");
}
}
//获取body
String body = new String(requestWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
if (StringUtils.hasLength(body)) {
sb.append(" -d '").append(body).append("'");
}
//输出到input
ActiveSpan.tag("input", sb.toString());
//输出到userId
ActiveSpan.tag("userid", BaseMethodUtil.getUserIdByHeader(request)+"");
//获取返回值body
String responseBody = new String(responseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
//输出到output
ActiveSpan.tag("output", responseBody);
} catch (Exception e) {
log.warn("fail to build http log", e);
} finally {
//这一行必须添加,否则就一直不返回
responseWrapper.copyBodyToResponse();
}
}
}
}
3、容器启动配置tag
-e SW_NAMESPACE=bg-e SW_SEARCHABLE_TAG_KEYS=http.method,status_code,db.type,db.instance,mq.queue,mq.topic,mq.broker,input,output,userid
需要企业微信机器人
-v D:\Code\k8s\kibana\alarm-settings.yml:/skywalking/config/alarm-settings.yml
npm install skywalking-client-js --save
import ClientMonitor from 'skywalking-client-js';
ClientMonitor.register({
collector: process.env.VUE_APP_PERMISSION_URL + '/ui',
service: process.env.VUE_APP_SW_NAME || 'op::ui',
pagePath: location.href,
serviceVersion: 'v1.0.0',
vue: Vue,
useFmp: true,
enableSPA: false,
traceTimeInterval: 10000,
apiErrors: true,
})
// 异常拦截器
Vue.config.errorHandler = (error) => {
console.error(error)
error.message += window.location.href
const _roles = store.state.user.roles
if (_roles) {
error.message += (_roles.name || '') + ' ' + _roles.number
}
ClientMonitor.reportFrameErrors({
collector: process.env.VUE_APP_PERMISSION_URL + '/ui',
service: process.env.VUE_APP_SW_NAME || 'op::ui',
pagePath: window.location.href,
vue: Vue,
serviceVersion: 'v1.0.0'
}, error)
}
// 路由拦截器
import ClientMonitor from 'skywalking-client-js'
ClientMonitor.customOptions.pagePath = location.origin + location.pathname + '#' + to.fullPath
server {
listen 80;
listen [::]:80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html-test;
index index.html index.htm;
}
location /ui/browser/ {
rewrite ^.+ui/?(.*)$ /$1 break;
include uwsgi_params;
proxy_pass xxxxxx;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
}
location /ui/v3/ {
rewrite ^.+ui/?(.*)$ /$1 break;
include uwsgi_params;
proxy_pass xxxxxxx;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
}
location /ui {
try_files $uri $uri/ /index.html;
alias /usr/share/nginx/html-test/ui;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
1、 删除索引后,记得删除对应的ES模板; 2、 VUE项目要根据实际情况,做sw服务的nginx的反向代理配置; 3、 skywalking如果遇到问题,可以优先升级最新版本;
本文分享自 NetCore 从壹开始 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!