2022-09-06 10:35:14 -06:00
|
|
|
package lg
|
2022-08-13 13:34:13 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
2022-08-14 13:40:02 -06:00
|
|
|
"os"
|
2022-08-23 21:24:13 -06:00
|
|
|
"strings"
|
2022-08-13 13:34:13 -06:00
|
|
|
|
|
|
|
"go.uber.org/multierr"
|
|
|
|
)
|
|
|
|
|
2023-01-09 11:30:02 -07:00
|
|
|
func Init(ctx context.Context, name string) (context.Context, func(context.Context) error) {
|
2022-08-13 18:59:15 -06:00
|
|
|
ctx, span := Span(ctx)
|
|
|
|
defer span.End()
|
|
|
|
|
2022-08-13 13:34:13 -06:00
|
|
|
stop := [3]func() error{
|
|
|
|
initLogger(name),
|
|
|
|
}
|
|
|
|
ctx, stop[1] = initMetrics(ctx, name)
|
|
|
|
ctx, stop[2] = initTracing(ctx, name)
|
|
|
|
|
|
|
|
reverse(stop[:])
|
|
|
|
|
2023-01-09 11:30:02 -07:00
|
|
|
return ctx, func(context.Context) error {
|
2022-08-13 13:34:13 -06:00
|
|
|
log.Println("flushing logs...")
|
|
|
|
errs := make([]error, len(stop))
|
|
|
|
for i, fn := range stop {
|
2022-08-13 18:59:15 -06:00
|
|
|
if fn != nil {
|
|
|
|
errs[i] = fn()
|
|
|
|
}
|
2022-08-13 13:34:13 -06:00
|
|
|
}
|
|
|
|
log.Println("all stopped.")
|
|
|
|
return multierr.Combine(errs...)
|
|
|
|
}
|
|
|
|
}
|
2022-08-14 13:40:02 -06:00
|
|
|
|
|
|
|
func env(name, defaultValue string) string {
|
2022-08-23 21:24:13 -06:00
|
|
|
name = strings.TrimSpace(name)
|
|
|
|
defaultValue = strings.TrimSpace(defaultValue)
|
|
|
|
if v := strings.TrimSpace(os.Getenv(name)); v != "" {
|
|
|
|
log.Println("# ", name, "=", v)
|
2022-08-14 13:40:02 -06:00
|
|
|
return v
|
|
|
|
}
|
2022-08-23 21:24:13 -06:00
|
|
|
log.Println("# ", name, "=", defaultValue, "(default)")
|
2022-08-14 13:40:02 -06:00
|
|
|
return defaultValue
|
|
|
|
}
|
2022-08-23 21:24:13 -06:00
|
|
|
|
|
|
|
type secret string
|
|
|
|
|
|
|
|
func (s secret) String() string {
|
|
|
|
if s == "" {
|
|
|
|
return "(nil)"
|
|
|
|
}
|
|
|
|
return "***"
|
|
|
|
}
|
|
|
|
func (s secret) Secret() string {
|
|
|
|
return string(s)
|
|
|
|
}
|
|
|
|
func envSecret(name, defaultValue string) secret {
|
|
|
|
name = strings.TrimSpace(name)
|
|
|
|
defaultValue = strings.TrimSpace(defaultValue)
|
|
|
|
if v := strings.TrimSpace(os.Getenv(name)); v != "" {
|
|
|
|
log.Println("# ", name, "=", secret(v))
|
|
|
|
return secret(v)
|
|
|
|
}
|
|
|
|
log.Println("# ", name, "=", secret(defaultValue), "(default)")
|
|
|
|
return secret(defaultValue)
|
|
|
|
}
|