feat: logging #20
15
main.go
15
main.go
@@ -2,6 +2,9 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"realdnydns/pkg/config"
|
||||
"realdnydns/pkg/dnsProvider"
|
||||
@@ -15,12 +18,24 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
|
||||
Level: slog.LevelInfo,
|
||||
}))
|
||||
|
||||
configClient := config.Config{}
|
||||
err := configClient.Load("config.yaml")
|
||||
if err != nil {
|
||||
logger.Error("Failed to load config file",
|
||||
slog.String("error", err.Error()))
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if configClient.LogLevel != "" {
|
||||
logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
|
||||
Level: slog.Level(config.LogLevelMap[strings.ToLower(configClient.LogLevel)]),
|
||||
}))
|
||||
}
|
||||
|
||||
var externalIpProvider externalIpProvider.ExternalIpProvider
|
||||
switch configClient.ExternalIPProvider.Type {
|
||||
case "plain":
|
||||
|
||||
@@ -3,7 +3,9 @@ package config
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
@@ -15,6 +17,7 @@ type Config struct {
|
||||
NotificationProvider NotificationProviderConfig `yaml:"notification_provider,omitempty"`
|
||||
Domains []DomainConfig `yaml:"domains"`
|
||||
CheckInterval string `yaml:"check_interval"`
|
||||
LogLevel string `yaml:"log_level"`
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -22,6 +25,18 @@ const (
|
||||
ScheduledMode = "Scheduled"
|
||||
)
|
||||
|
||||
var LogLevelMap = map[string]slog.Level{
|
||||
"debug": slog.LevelDebug,
|
||||
"info": slog.LevelInfo,
|
||||
"warn": slog.LevelWarn,
|
||||
"error": slog.LevelError,
|
||||
}
|
||||
|
||||
func isValidLogLevel(level string) bool {
|
||||
_, ok := LogLevelMap[strings.ToLower(level)]
|
||||
return ok
|
||||
}
|
||||
|
||||
type DomainConfig struct {
|
||||
TLD string `yaml:"tld"`
|
||||
Subdomains []string `yaml:"subdomains"`
|
||||
@@ -68,5 +83,9 @@ func (c *Config) validate() error {
|
||||
return errors.New("check interval must be set when mode is 'Scheduled'")
|
||||
}
|
||||
|
||||
if c.LogLevel != "" && !isValidLogLevel(c.LogLevel) {
|
||||
return fmt.Errorf("log level must be one of 'debug', 'info', 'warn', 'error', but got %s", c.LogLevel)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user