serviceconf.go 1.4 KB

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