logger_config.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package logger
  2. import "log/slog"
  3. type SMTPClient interface {
  4. Send(recipient string, subject string, content string, html bool) error
  5. }
  6. type Config struct {
  7. // stdout config
  8. stdoutLogEnabled bool
  9. stdoutLogLevel slog.Level // INFO by default
  10. // file config
  11. fileLogEnabled bool
  12. fileLogLevel slog.Level // INFO by default
  13. filepath string
  14. // email config
  15. emailLogEnabled bool
  16. emailLogLevel slog.Level // INFO by default
  17. smtpClient SMTPClient
  18. emailRecipient string
  19. emailSubject string
  20. }
  21. type ConfigOption func(*Config)
  22. type ConfigOptions []ConfigOption
  23. func (s *ConfigOptions) Add(option ConfigOption) {
  24. *s = append(*s, option)
  25. }
  26. func NewConfig(opts ...ConfigOption) Config {
  27. c := &Config{}
  28. for _, opt := range opts {
  29. opt(c)
  30. }
  31. return *c
  32. }
  33. // stdout
  34. func WithStdoutLogEnabled(enabled bool) ConfigOption {
  35. return func(s *Config) {
  36. s.stdoutLogEnabled = enabled
  37. }
  38. }
  39. func WithStdoutLogLevel(level string) ConfigOption {
  40. return func(s *Config) {
  41. var l slog.Level
  42. if err := l.UnmarshalText([]byte(level)); err == nil {
  43. s.stdoutLogLevel = l
  44. }
  45. }
  46. }
  47. // file
  48. func WithFileLogEnabled(enabled bool) ConfigOption {
  49. return func(s *Config) {
  50. s.fileLogEnabled = enabled
  51. }
  52. }
  53. func WithFileLogLevel(level string) ConfigOption {
  54. return func(s *Config) {
  55. var l slog.Level
  56. if err := l.UnmarshalText([]byte(level)); err == nil {
  57. s.fileLogLevel = l
  58. }
  59. }
  60. }
  61. func WithFilepath(path string) ConfigOption {
  62. return func(s *Config) {
  63. s.filepath = path
  64. }
  65. }
  66. // email
  67. func WithEmailLogEnabled(enabled bool) ConfigOption {
  68. return func(s *Config) {
  69. s.emailLogEnabled = enabled
  70. }
  71. }
  72. func WithEmailLogLevel(level string) ConfigOption {
  73. return func(s *Config) {
  74. var l slog.Level
  75. if err := l.UnmarshalText([]byte(level)); err == nil {
  76. s.emailLogLevel = l
  77. }
  78. }
  79. }
  80. func WithEmailRecipient(email string) ConfigOption {
  81. return func(s *Config) {
  82. s.emailRecipient = email
  83. }
  84. }
  85. func WithEmailSubject(subject string) ConfigOption {
  86. return func(s *Config) {
  87. s.emailSubject = subject
  88. }
  89. }
  90. func WithSMTPClient(c SMTPClient) ConfigOption {
  91. return func(s *Config) {
  92. s.smtpClient = c
  93. }
  94. }