Golang弹性APM - cronjob的保存事务
我需要将弹性APM连接到我的cronjob
,但是当我跟踪documentation for APM
时,我没有看到任何事务,甚至没有注册服务。
如何连接APM
并为cronjob
而不是api
注册事务
main.go
package main
import (
"context"
"errors"
"math/rand"
"time"
"go.elastic.co/apm/v2"
)
func main() {
// export ELASTIC_APM_SERVICE_NAME=test
t := apm.DefaultTracer().StartTransaction("test-name", "test-group")
c := apm.ContextWithTransaction(context.Background(), t)
worker(c)
t.End()
time.Sleep(time.Second * 5)
}
func worker(c context.Context) {
span, c := apm.StartSpan(c, "one", "test-type")
e := apm.DefaultTracer().Recovered(errors.New("test-error"))
e.SetSpan(span)
e.Send()
// do some work
time.Sleep(time.Duration(rand.Intn(300-100)+300) * time.Millisecond)
span.End()
two(c)
}
func two(c context.Context) {
span, _ := apm.StartSpan(c, "two", "test-type")
// do some other work
time.Sleep(time.Duration(rand.Intn(100-50)+100) * time.Millisecond)
span.End()
}
docker-compose.yaml
在本地运行APM
version: '3.8'
services:
apm-server:
image: docker.elastic.co/apm/apm-server:7.15.0
cap_add: ["CHOWN", "DAC_OVERRIDE", "SETGID", "SETUID"]
cap_drop: ["ALL"]
ports:
- 8200:8200
command: >
apm-server -e
-E apm-server.rum.enabled=true
-E setup.kibana.host=kibana:5601
-E setup.template.settings.index.number_of_replicas=0
-E apm-server.kibana.enabled=true
-E apm-server.kibana.host=kibana:5601
-E output.elasticsearch.hosts=["elasticsearch:9200"]
healthcheck:
interval: 10s
retries: 12
test: curl --write-out 'HTTP %{http_code}' --fail --silent --output /dev/null http://localhost:8200/
networks:
- elastic
elasticsearch:
container_name: elasticsearch
image: docker.elastic.co/elasticsearch/elasticsearch:7.15.0
ports:
- 9200:9200
environment:
- xpack.monitoring.enabled=true
- xpack.watcher.enabled=false
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- discovery.type=single-node
networks:
- elastic
kibana:
container_name: kibana
image: docker.elastic.co/kibana/kibana:7.15.0
ports:
- 5601:5601
depends_on:
- elasticsearch
environment:
- ELASTICSEARCH_URL=http://localhost:9200
- xpack.apm.enabled=false
networks:
- elastic
networks:
elastic:
driver: bridge
发布于 2022-09-26 01:34:15
您的跟踪程序可能没有在作业退出之前发送事务。要确保做到这一点,请在time.Sleep
中的main()
中添加(或替换)如下:
apm.DefaultTracer().Flush(nil)
https://stackoverflow.com/questions/73846719
复制相似问题