Home > Software engineering >  Golang Elastic APM - save transactions of cronjob
Golang Elastic APM - save transactions of cronjob

Time:09-27

Golang Elastic APM - save transactions of cronjob

I need to connect Elastic APM to my cronjob however I when I follow documentation for APM I see no transactions or even service registered.

How can I connect APM and register transactions for cronjob and not for 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 to run APM locally
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

CodePudding user response:

Your tracer is probably not sending the transaction before the job exits. To ensure it does, add after (or replace) the time.Sleep in main() with:

apm.DefaultTracer().Flush(nil)
  • Related