依赖

web框架(要求2.7+)

1
"koa": "^2.13.1"

日志(基于tcp协议)

1
2
"log4js": "^3.0.5",
"log4js-logstash-tcp": "^2.0.0"

zipkin

1
2
"zipkin-instrumentation-koa": "^0.22.0",
"zipkin-transport-http": "^0.22.0"

代码(ziplin部分)

1
2
3
4
5
6
7
8
9
10
11
# 下游(上游略,上游改localServiceName即可)
const {Tracer, BatchRecorder, ExplicitContext} = require('zipkin');
const {koaMiddleware} = require('zipkin-instrumentation-koa');
const ctxImpl = new ExplicitContext();
const recorder = new BatchRecorder({
logger: new HttpLogger({
endpoint: 'http://192.168.56.100:9411/api/v1/spans' // zipkin地址
})});
const tracer = new Tracer({recorder, ctxImpl, localServiceName: 'sapi_carmodel'});
const app = new Koa();
app.use(koaMiddleware({tracer}))

代码(log部分)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var log4js = require('log4js');
log4js.configure({
"appenders": [
{
"category": "tests",
"type": "log4js-logstash-tcp",
"host": "localhost",
"port": 5050,
"fields": {
"instance": "MyAwsInstance",
"source": "myApp",
"environment": "development"
}
},
{
"category": "tests",
"type": "console"
}
],
"levels": {
"tests": "DEBUG"
}
});

logstash.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
input {
tcp {
host => "0.0.0.0"
codec => json_lines
port => 5050
type => "debug"
}
}
filter{
if [type] == "debug" {
json {
source => "message"
remove_field => ["message"]
}
}
}
output {
elasticsearch {
hosts => ["es:9200"]
action => "index"
codec => json
index => "sopei-%{type}-%{+YYYY.MM.dd}"
template_name => "sopei"
}
}

测试代码(上游服务发送请求)

1
2
3
4
5
6
7
8
// 测试接口并将_trace_id以header方式传过去,这里用ExplicitContext(需手动传值ctx.request._trace_id),CLSContext不好使而且没找到原因
router.get('/tests', async (ctx)=>{
const result = await ctx.rest.get(下游接口);
var log = log4js.getLogger('tests');
log.debug(result);
return ctx.send('success',result)
});
# 下游从header获取ctx.request._trace_id

ps:这里目前得到的message格式不太对,待改

补充docker-compose中的zipkin部分

(关于zipkin,官方提供了三种存储模式,docker-compose||zipkin-storage)

1
2
3
4
5
6
7
8
9
10
11
zipkin:
image: openzipkin/zipkin:2.22.1
container_name: zipkin
links:
- elasticsearch:es
environment:
- STORAGE_TYPE=elasticsearch
- ES_HOSTS=es:9200
ports:
# Port used for the Zipkin UI and HTTP Api
- 9411:9411