Проблемы с интеграцией Beego и Newrelic

Я создаю веб-приложение на Go с помощью Beego (https://beego.me).

У меня есть требование фиксировать показатели мониторинга и измерения приложений в Newrelic, а также иметь возможность просматривать все транзакции в Newrelic.

Я следил за этой документацией и использую Beego GoRelic для инициализации агента Newrelic в моем коде.

Вот мой класс router.go -

import (
    "github.com/astaxie/beego"
    "github.com/yvasiyarov/beego_gorelic"
)

func init() {
    beego_gorelic.InitNewrelicAgent()
    beego.Router("path", &controller{}, "functionName") // code broken intentionally
}

В моем app.conf я указал лицензионный ключ newrelic и имя приложения, например:

NewrelicLicense = "key"
newrelicAppname = "App Name"

Когда я запускаю приложение в dev режиме, я вижу печатаемые метрики, например:

Send data:{
    "agent": {
        "host": "localhost",
        "version": "0.0.6",
        "pid": 13942
    },
    "components": [
        {
            "name": "Name",
            "guid": "com.github.yvasiyarov.GoRelic",
            "duration": 60,
            "metrics": {
                "Component/Runtime/GC/GCTime/Max[nanoseconds]": 0,
                "Component/Runtime/GC/GCTime/Mean[nanoseconds]": 0,
                "Component/Runtime/GC/GCTime/Min[nanoseconds]": 0,
                "Component/Runtime/GC/GCTime/Percentile95[nanoseconds]": 0,
                "Component/Runtime/GC/NumberOfGCCalls[calls]": 0,
                "Component/Runtime/GC/PauseTotalTime[nanoseconds]": 0,
                "Component/Runtime/General/NOCgoCalls[calls]": 1,
                "Component/Runtime/General/NOGoroutines[goroutines]": 6,
                "Component/Runtime/Memory/InUse/Heap[bytes]": 538368,
                "Component/Runtime/Memory/InUse/MCacheInuse[bytes]": 13888,
                "Component/Runtime/Memory/InUse/MSpanInuse[bytes]": 13192,
                "Component/Runtime/Memory/InUse/Stack[bytes]": 360448,
                "Component/Runtime/Memory/InUse/Total[bytes]": 538368,
                "Component/Runtime/Memory/Operations/NoFrees[frees]": 128,
                "Component/Runtime/Memory/Operations/NoMallocs[mallocs]": 2903,
                "Component/Runtime/Memory/Operations/NoPointerLookups[lookups]": 0,
                "Component/Runtime/Memory/SysMem/BuckHash[bytes]": 3078,
                "Component/Runtime/Memory/SysMem/Heap[bytes]": 66748416,
                "Component/Runtime/Memory/SysMem/MCache[bytes]": 16384,
                "Component/Runtime/Memory/SysMem/MSpan[bytes]": 16384,
                "Component/Runtime/Memory/SysMem/Stack[bytes]": 360448,
                "Component/Runtime/Memory/SysMem/Total[bytes]": 69928960,
                "Component/http/responseTime/max[ms]": 0,
                "Component/http/responseTime/mean[ms]": 0,
                "Component/http/responseTime/min[ms]": 0,
                "Component/http/responseTime/percentile75[ms]": 0,
                "Component/http/responseTime/percentile90[ms]": 0,
                "Component/http/responseTime/percentile95[ms]": 0,
                "Component/http/throughput/1minute[rps]": 0,
                "Component/http/throughput/rateMean[rps]": 0
            }
        }
    ],
    "URL": "https://platform-api.newrelic.com/platform/v1/metrics"
} 

Это говорит мне, что новый агент реликвии запущен и собирает данные.

Я не писал другого кода для интеграции Newrelic в свой код, кроме этого.

Метрики не передаются в Newrelic с этими настройками и настройками, и я не могу найти лучшую документацию для решения этой проблемы.

Что мне не хватает?

Кроме того, есть ли другой способ интегрировать newrelic в приложение Beego?

P.S. Я не использую фильтры Beego в качестве препроцессоров, но использую метод prepare в контроллерах для предварительной обработки запросов. Однако эта библиотека, похоже, добавляет 2 фильтра в структуру Beego, например:

    beego.InsertFilter("*", beego.BeforeRouter, InitNewRelicTimer, false)
    beego.InsertFilter("*", beego.FinishRouter, ReportMetricsToNewrelic, false)

Дополнительные журналы:

2020/01/09 20:13:29 Init GC metrics collection. Poll interval 10 seconds.
2020/01/09 20:13:29 Init memory allocator metrics collection. Poll interval 60 seconds.
2020/01/09 20:13:29 Init HTTP metrics collection.
2020/01/09 20:13:29 [I] [gorelic.go:71] NewRelic agent started 
2020/01/09 20:13:29 Can not get metrica: Runtime/System/Threads, got error:this metrica was not implemented yet for darwin
2020/01/09 20:13:29 Can not get metrica: Runtime/System/FDSize, got error:this metrica was not implemented yet for darwin
2020/01/09 20:13:29 Can not get metrica: Runtime/System/Memory/VmPeakSize, got error:this metrica was not implemented yet for darwin
2020/01/09 20:13:29 Can not get metrica: Runtime/System/Memory/VmCurrent, got error:this metrica was not implemented yet for darwin
2020/01/09 20:13:29 Can not get metrica: Runtime/System/Memory/RssPeak, got error:this metrica was not implemented yet for darwin
2020/01/09 20:13:29 Can not get metrica: Runtime/System/Memory/RssCurrent, got error:this metrica was not implemented yet for darwin
2020/01/09 20:13:29 Send data:{
    "agent": {
        "host": "localhost",
        "version": "0.0.6",
        "pid": 14931
    },
    "components": [
        {
            "name": "App Name",
            "guid": "com.github.yvasiyarov.GoRelic",
            "duration": 60,
            "metrics": {
                "Component/Runtime/GC/GCTime/Max[nanoseconds]": 0,
                "Component/Runtime/GC/GCTime/Mean[nanoseconds]": 0,
                "Component/Runtime/GC/GCTime/Min[nanoseconds]": 0,
                "Component/Runtime/GC/GCTime/Percentile95[nanoseconds]": 0,
                "Component/Runtime/GC/NumberOfGCCalls[calls]": 0,
                "Component/Runtime/GC/PauseTotalTime[nanoseconds]": 0,
                "Component/Runtime/General/NOCgoCalls[calls]": 1,
                "Component/Runtime/General/NOGoroutines[goroutines]": 8,
                "Component/Runtime/Memory/InUse/Heap[bytes]": 591616,
                "Component/Runtime/Memory/InUse/MCacheInuse[bytes]": 13888,
                "Component/Runtime/Memory/InUse/MSpanInuse[bytes]": 16592,
                "Component/Runtime/Memory/InUse/Stack[bytes]": 393216,
                "Component/Runtime/Memory/InUse/Total[bytes]": 591616,
                "Component/Runtime/Memory/Operations/NoFrees[frees]": 132,
                "Component/Runtime/Memory/Operations/NoMallocs[mallocs]": 2988,
                "Component/Runtime/Memory/Operations/NoPointerLookups[lookups]": 0,
                "Component/Runtime/Memory/SysMem/BuckHash[bytes]": 3078,
                "Component/Runtime/Memory/SysMem/Heap[bytes]": 66715648,
                "Component/Runtime/Memory/SysMem/MCache[bytes]": 16384,
                "Component/Runtime/Memory/SysMem/MSpan[bytes]": 32768,
                "Component/Runtime/Memory/SysMem/Stack[bytes]": 393216,
                "Component/Runtime/Memory/SysMem/Total[bytes]": 69928960,
                "Component/http/responseTime/max[ms]": 0,
                "Component/http/responseTime/mean[ms]": 0,
                "Component/http/responseTime/min[ms]": 0,
                "Component/http/responseTime/percentile75[ms]": 0,
                "Component/http/responseTime/percentile90[ms]": 0,
                "Component/http/responseTime/percentile95[ms]": 0,
                "Component/http/throughput/1minute[rps]": 0,
                "Component/http/throughput/rateMean[rps]": 0
            }
        }
    ],
    "URL": "https://platform-api.newrelic.com/platform/v1/metrics"
} 

Может в этом проблема? Как я могу это решить?


person saarthak gupta    schedule 09.01.2020    source источник
comment
В журнале должно быть больше данных. Вы можете этим поделиться?   -  person Dmitry Harnitski    schedule 09.01.2020
comment
Привет, @DmitryHarnitski, к сожалению, это полный журнал, который печатается в режиме dev.   -  person saarthak gupta    schedule 09.01.2020
comment
попробуйте это beego.BConfig.RunMode == "dev", чтобы включить подробный режим.   -  person Dmitry Harnitski    schedule 09.01.2020
comment
@DmitryHarnitski Я добавил дополнительные логи в вопрос. Однако я думаю, что у меня есть решение. Оказывается, я искал не в том месте, и этот plugin фактически публикует данные в разделе Plugins NewRelic (я смотрел на APM, так как это то, что мне нужно).   -  person saarthak gupta    schedule 09.01.2020
comment
Я продолжу тратить время на подключение плагина NewRelic go для публикации показателей в APM и отвечу здесь, когда он у меня заработает. Большое спасибо за вашу помощь :)   -  person saarthak gupta    schedule 09.01.2020


Ответы (1)


Я отвечаю на свой вопрос, так как считаю, что нашел способ, и он может помочь и кому-то другому - видимо, это просто вопрос того, чтобы усерднее искать существующие плагины. Я обнаружил, что этот плагин: https://github.com/sergeylanzman/newrelic_beego делает именно то, что мне нужно .

Если мы наблюдаем код, то автор создал 3 метода -

  1. StartTransaction
  2. NameTransaction
  3. EndTransaction

и вставляет их как фильтры в среду Beego. Под капотом автор использовал официальный агент Newrelic Go (https://github.com/newrelic/go-agent) и использует транзакции для передачи данных APM.

Вот пример кода из плагина, который регистрирует 3 фильтра -

    beego.InsertFilter("*", beego.BeforeRouter, StartTransaction, false)
    beego.InsertFilter("*", beego.AfterExec, NameTransaction, false)
    beego.InsertFilter("*", beego.FinishRouter, EndTransaction, false)
    beego.Info("NewRelic agent start")

Он использует структуру контекста Beego для отслеживания данных транзакции по функциям (как указано в документации по контексту).

Я буду продолжать изучать этот вопрос и добавлять отслеживание внешних вызовов, вызовов БД и распределенной трассировки по мере нашего прогресса, но это решило мою проблему.

P.S. Я прекратил использовать плагин, который использовал ранее, поскольку этот пакет также сообщает статистику Go Runtime в NewRelic, что делает другой плагин устаревшим (личное мнение :))

person saarthak gupta    schedule 09.01.2020