config.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package logger
  2. import (
  3. "errors"
  4. "log/slog"
  5. "os"
  6. "strings"
  7. "github.com/mattn/go-isatty"
  8. "github.com/imgproxy/imgproxy/v3/ensure"
  9. "github.com/imgproxy/imgproxy/v3/env"
  10. "github.com/imgproxy/imgproxy/v3/logger/syslog"
  11. )
  12. var (
  13. IMGPROXY_LOG_FORMAT = env.Describe("IMGPROXY_LOG_FORMAT", "pretty|structured|json|gcp")
  14. IMGPROXY_LOG_LEVEL = env.Describe("IMGPROXY_LOG_LEVEL", "debug|info|warn|error")
  15. )
  16. type Config struct {
  17. Level slog.Leveler
  18. Format Format
  19. Syslog syslog.Config
  20. }
  21. func NewDefaultConfig() Config {
  22. o := Config{
  23. Level: slog.LevelInfo,
  24. Format: FormatStructured,
  25. Syslog: syslog.NewDefaultConfig(),
  26. }
  27. if isatty.IsTerminal(os.Stdout.Fd()) {
  28. o.Format = FormatPretty
  29. }
  30. return o
  31. }
  32. func LoadConfigFromEnv(o *Config) (*Config, error) {
  33. o = ensure.Ensure(o, NewDefaultConfig)
  34. var logFormat, logLevel string
  35. _, slErr := syslog.LoadConfigFromEnv(&o.Syslog)
  36. err := errors.Join(
  37. slErr,
  38. env.String(&logFormat, IMGPROXY_LOG_FORMAT),
  39. env.String(&logLevel, IMGPROXY_LOG_LEVEL),
  40. )
  41. if logFormat != "" {
  42. o.Format = parseFormat(logFormat)
  43. }
  44. if logLevel != "" {
  45. o.Level = parseLevel(logLevel)
  46. }
  47. // Load syslog config
  48. return o, err
  49. }
  50. func (c *Config) Validate() error {
  51. return c.Syslog.Validate()
  52. }
  53. func parseFormat(str string) Format {
  54. switch str {
  55. case "pretty":
  56. return FormatPretty
  57. case "structured":
  58. return FormatStructured
  59. case "json":
  60. return FormatJSON
  61. case "gcp":
  62. return FormatGCP
  63. default:
  64. if isatty.IsTerminal(os.Stdout.Fd()) {
  65. return FormatPretty
  66. }
  67. return FormatStructured
  68. }
  69. }
  70. func parseLevel(str string) slog.Level {
  71. switch strings.ToLower(str) {
  72. case "debug":
  73. return slog.LevelDebug
  74. case "warn":
  75. return slog.LevelWarn
  76. case "error":
  77. return slog.LevelError
  78. default:
  79. return slog.LevelInfo
  80. }
  81. }