登录
首页 >  Golang >  Go问答

Golang Elastic APM - 保存 cronjob 的事务

来源:stackoverflow

时间:2024-04-16 18:18:21 367浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《Golang Elastic APM - 保存 cronjob 的事务》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

golang elastic apm - 保存 cronjob 事务

我需要将 elastic apm 连接到我的 cronjob,但是当我按照 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

正确答案


您的跟踪器可能不会在作业退出之前发送事务。为了确保它确实如此,请在 main() 中的 time.sleep 之后添加(或替换)为:

apm.DefaultTracer().Flush(nil)

好了,本文到此结束,带大家了解了《Golang Elastic APM - 保存 cronjob 的事务》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>