config.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package syslog
  2. import (
  3. "errors"
  4. "fmt"
  5. "log/slog"
  6. "strings"
  7. "github.com/imgproxy/imgproxy/v3/config/configurators"
  8. "github.com/imgproxy/imgproxy/v3/ensure"
  9. )
  10. type Config struct {
  11. Enabled bool
  12. Level slog.Leveler
  13. Network string
  14. Addr string
  15. Tag string
  16. }
  17. func NewDefaultConfig() Config {
  18. return Config{
  19. Enabled: false,
  20. Level: slog.LevelInfo,
  21. Tag: "imgproxy",
  22. }
  23. }
  24. func LoadConfigFromEnv(c *Config) *Config {
  25. c = ensure.Ensure(c, NewDefaultConfig)
  26. configurators.Bool(&c.Enabled, "IMGPROXY_SYSLOG_ENABLE")
  27. configurators.String(&c.Network, "IMGPROXY_SYSLOG_NETWORK")
  28. configurators.String(&c.Addr, "IMGPROXY_SYSLOG_ADDRESS")
  29. configurators.String(&c.Tag, "IMGPROXY_SYSLOG_TAG")
  30. var levelStr string
  31. configurators.String(&levelStr, "IMGPROXY_SYSLOG_LEVEL")
  32. if levelStr != "" {
  33. c.Level = parseLevel(levelStr)
  34. }
  35. return c
  36. }
  37. func (c *Config) Validate() error {
  38. if !c.Enabled {
  39. return nil
  40. }
  41. if c.Network != "" && c.Addr == "" {
  42. return errors.New("Syslog address is required if syslog network is set")
  43. }
  44. return nil
  45. }
  46. func parseLevel(str string) slog.Level {
  47. switch strings.ToLower(str) {
  48. case "debug":
  49. return slog.LevelDebug
  50. case "info":
  51. return slog.LevelInfo
  52. case "warn":
  53. return slog.LevelWarn
  54. case "error":
  55. return slog.LevelError
  56. case "crit":
  57. return slog.LevelError + 8
  58. default:
  59. slog.Warn(fmt.Sprintf("Syslog level '%s' is invalid, 'info' is used", str))
  60. return slog.LevelInfo
  61. }
  62. }