feat Prometheus
This commit is contained in:
58
module/prometheus.go
Normal file
58
module/prometheus.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package module
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"git.hlsq.asia/mmorpg/service-common/config"
|
||||||
|
"git.hlsq.asia/mmorpg/service-common/log"
|
||||||
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Prometheus 普罗米修斯模块
|
||||||
|
type Prometheus struct {
|
||||||
|
wg *sync.WaitGroup
|
||||||
|
server *http.Server
|
||||||
|
metricCfg *config.MetricConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Prometheus) Init() error {
|
||||||
|
m.wg = &sync.WaitGroup{}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Prometheus) Start() error {
|
||||||
|
m.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer m.wg.Done()
|
||||||
|
m.server = &http.Server{
|
||||||
|
Addr: fmt.Sprintf("%v:%v", m.metricCfg.Prometheus.Address, m.metricCfg.Prometheus.Port),
|
||||||
|
Handler: promhttp.Handler(),
|
||||||
|
}
|
||||||
|
if err := m.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
log.Errorf("prometheus server failed: %v", err.Error())
|
||||||
|
}
|
||||||
|
log.Infof("prometheus server stop.")
|
||||||
|
}()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Prometheus) Stop() error {
|
||||||
|
if err := m.server.Shutdown(context.Background()); err != nil {
|
||||||
|
log.Errorf("stop prometheus server failed: %v", err)
|
||||||
|
}
|
||||||
|
m.wg.Wait()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Prometheus) Bind(data ...any) Module {
|
||||||
|
if data == nil || len(data) == 0 {
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
if mc, ok := data[0].(*config.MetricConfig); ok {
|
||||||
|
m.metricCfg = mc
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user