1
0

configuration.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package honeybadger
  2. import (
  3. "log"
  4. "os"
  5. "strconv"
  6. "time"
  7. )
  8. // The Logger interface is implemented by the standard log package and requires
  9. // a limited subset of the interface implemented by log.Logger.
  10. type Logger interface {
  11. Printf(format string, v ...interface{})
  12. }
  13. // Configuration manages the configuration for the client.
  14. type Configuration struct {
  15. APIKey string
  16. Root string
  17. Env string
  18. Hostname string
  19. Endpoint string
  20. Timeout time.Duration
  21. Logger Logger
  22. Backend Backend
  23. }
  24. func (c1 *Configuration) update(c2 *Configuration) *Configuration {
  25. if c2.APIKey != "" {
  26. c1.APIKey = c2.APIKey
  27. }
  28. if c2.Root != "" {
  29. c1.Root = c2.Root
  30. }
  31. if c2.Env != "" {
  32. c1.Env = c2.Env
  33. }
  34. if c2.Hostname != "" {
  35. c1.Hostname = c2.Hostname
  36. }
  37. if c2.Endpoint != "" {
  38. c1.Endpoint = c2.Endpoint
  39. }
  40. if c2.Timeout > 0 {
  41. c1.Timeout = c2.Timeout
  42. }
  43. if c2.Logger != nil {
  44. c1.Logger = c2.Logger
  45. }
  46. if c2.Backend != nil {
  47. c1.Backend = c2.Backend
  48. }
  49. return c1
  50. }
  51. func newConfig(c Configuration) *Configuration {
  52. config := &Configuration{
  53. APIKey: getEnv("HONEYBADGER_API_KEY"),
  54. Root: getPWD(),
  55. Env: getEnv("HONEYBADGER_ENV"),
  56. Hostname: getHostname(),
  57. Endpoint: getEnv("HONEYBADGER_ENDPOINT", "https://api.honeybadger.io"),
  58. Timeout: getTimeout(),
  59. Logger: log.New(os.Stderr, "[honeybadger] ", log.Flags()),
  60. }
  61. config.update(&c)
  62. if config.Backend == nil {
  63. config.Backend = newServerBackend(config)
  64. }
  65. return config
  66. }
  67. func getTimeout() time.Duration {
  68. if env := getEnv("HONEYBADGER_TIMEOUT"); env != "" {
  69. if ns, err := strconv.ParseInt(env, 10, 64); err == nil {
  70. return time.Duration(ns)
  71. }
  72. }
  73. return 3 * time.Second
  74. }
  75. func getEnv(key string, fallback ...string) (val string) {
  76. val = os.Getenv(key)
  77. if val == "" && len(fallback) > 0 {
  78. return fallback[0]
  79. }
  80. return
  81. }
  82. func getHostname() (hostname string) {
  83. if val, err := os.Hostname(); err == nil {
  84. hostname = val
  85. }
  86. return getEnv("HONEYBADGER_HOSTNAME", hostname)
  87. }
  88. func getPWD() (pwd string) {
  89. if val, err := os.Getwd(); err == nil {
  90. pwd = val
  91. }
  92. return getEnv("HONEYBADGER_ROOT", pwd)
  93. }