config.go 1.5 KB

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