Golang弹性APM-保存cronjob的事务

ebdffaop  于 2022-10-06  发布在  Go
关注(0)|答案(1)|浏览(157)

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
epggiuax

epggiuax1#

在作业退出之前,您的跟踪程序可能没有发送事务。为确保正确,请在main()中的time.Sleep之后添加(或替换)以下内容:

apm.DefaultTracer().Flush(nil)

相关问题