Go 1.9 prometheus 모니터링 작은 인 스 턴 스 접속
5643 단어 Golang
package main
import (
"bytes"
"fmt"
"net/http"
"strings"
"sync/atomic"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/expfmt"
)
type statusCollect struct {
reqDesc *prometheus.CounterVec
respsizeDesc *prometheus.Desc
respsizevalue int64
}
func (s *statusCollect) ReqAdd(code, method string) {
s.reqDesc.WithLabelValues(code, method).Inc()
}
func (s *statusCollect) ReqSizeAdd(size int64) {
atomic.AddInt64(&s.respsizevalue, size)
}
func (s *statusCollect) Describe(ch chan.Desc) {
ch .respsizeDesc
s.reqDesc.Describe(ch)
}
func (s *statusCollect) Collect(ch chan.Metric) {
ch .MustNewConstMetric(s.respsizeDesc, prometheus.CounterValue, float64(s.respsizevalue))
s.reqDesc.Collect(ch)
}
func NewStatusCollect() *statusCollect {
opts := prometheus.CounterOpts{Namespace: "Test", Subsystem: "http", Name: "request count", Help: "requst count"}
return &statusCollect{
reqDesc: prometheus.NewCounterVec(opts, []string{"code", "method"}),
respsizeDesc: prometheus.NewDesc("Namespace_http_respsize_count", "http respsize count", nil, nil),
}
}
const (
contentTypeHeader = "Content-Type"
contentLengthHeader = "Content-Length"
)
func main() {
status := NewStatusCollect()
regist := prometheus.NewRegistry()
regist.MustRegister(status)
http.HandleFunc("/api/metric", func(w http.ResponseWriter, r *http.Request) {
status.ReqAdd("200", strings.ToLower(r.Method))
entry, err := regist.Gather()
if err != nil {
http.Error(w, "An error has occurred during metrics collection:
"+err.Error(), http.StatusInternalServerError)
return
}
buf := bytes.NewBuffer(nil)
contentType := expfmt.Negotiate(r.Header)
enc := expfmt.NewEncoder(buf, contentType)
for _, met := range entry {
if err := enc.Encode(met); err != nil {
http.Error(w, "An error has occurred during metrics encoding:
"+err.Error(), http.StatusInternalServerError)
return
}
}
if buf.Len() == 0 {
http.Error(w, "No metrics encoded, last error:
"+err.Error(), http.StatusInternalServerError)
return
}
status.ReqSizeAdd(int64(buf.Len()))
header := w.Header()
header.Set(contentTypeHeader, string(contentType))
header.Set(contentLengthHeader, fmt.Sprint(buf.Len()))
w.Write(buf.Bytes())
})
http.ListenAndServe(":1789", nil)
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Golang 구현 대기열 및 스택대기열: 스택: github 주소:https://github.com/golibec/Lstruct.git 후속적으로 각종 데이터 구조와 주류 알고리즘을 지속적으로 보완할 것이다....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.