serviceconf.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 means development mode.
  11. DevMode = "dev"
  12. // TestMode means test mode.
  13. TestMode = "test"
  14. // PreMode means pre-release mode.
  15. PreMode = "pre"
  16. // ProMode means production mode.
  17. ProMode = "pro"
  18. )
  19. // A ServiceConf is a service config.
  20. type ServiceConf struct {
  21. Name string
  22. Log logx.LogConf
  23. Mode string `json:",default=pro,options=dev|test|rt|pre|pro"`
  24. MetricsUrl string `json:",optional"`
  25. Prometheus prometheus.Config `json:",optional"`
  26. }
  27. // MustSetUp sets up the service, exits on error.
  28. func (sc ServiceConf) MustSetUp() {
  29. if err := sc.SetUp(); err != nil {
  30. log.Fatal(err)
  31. }
  32. }
  33. // SetUp sets up the service.
  34. func (sc ServiceConf) SetUp() error {
  35. if len(sc.Log.ServiceName) == 0 {
  36. sc.Log.ServiceName = sc.Name
  37. }
  38. if err := logx.SetUp(sc.Log); err != nil {
  39. return err
  40. }
  41. sc.initMode()
  42. prometheus.StartAgent(sc.Prometheus)
  43. if len(sc.MetricsUrl) > 0 {
  44. stat.SetReportWriter(stat.NewRemoteWriter(sc.MetricsUrl))
  45. }
  46. return nil
  47. }
  48. func (sc ServiceConf) initMode() {
  49. switch sc.Mode {
  50. case DevMode, TestMode, PreMode:
  51. load.Disable()
  52. stat.SetReporter(nil)
  53. }
  54. }