serviceconf.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package service
  2. import (
  3. "log"
  4. "github.com/tal-tech/go-zero/core/load"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. "github.com/tal-tech/go-zero/core/prometheus"
  7. "github.com/tal-tech/go-zero/core/stat"
  8. )
  9. const (
  10. DevMode = "dev"
  11. TestMode = "test"
  12. PreMode = "pre"
  13. ProMode = "pro"
  14. )
  15. type ServiceConf struct {
  16. Name string
  17. Log logx.LogConf
  18. Mode string `json:",default=pro,options=dev|test|pre|pro"`
  19. MetricsUrl string `json:",optional"`
  20. Prometheus prometheus.Config `json:",optional"`
  21. }
  22. func (sc ServiceConf) MustSetUp() {
  23. if err := sc.SetUp(); err != nil {
  24. log.Fatal(err)
  25. }
  26. }
  27. func (sc ServiceConf) SetUp() error {
  28. if len(sc.Log.ServiceName) == 0 {
  29. sc.Log.ServiceName = sc.Name
  30. }
  31. if err := logx.SetUp(sc.Log); err != nil {
  32. return err
  33. }
  34. sc.initMode()
  35. prometheus.StartAgent(sc.Prometheus)
  36. if len(sc.MetricsUrl) > 0 {
  37. stat.SetReportWriter(stat.NewRemoteWriter(sc.MetricsUrl))
  38. }
  39. return nil
  40. }
  41. func (sc ServiceConf) initMode() {
  42. switch sc.Mode {
  43. case DevMode, TestMode, PreMode:
  44. load.Disable()
  45. stat.SetReporter(nil)
  46. }
  47. }