Enhance logging and error handling in configuration loading, content fetching, and AI reply generation

This commit is contained in:
2025-03-01 05:22:45 +01:00
parent f349057975
commit 459422bc60
4 changed files with 216 additions and 16 deletions

View File

@@ -2,8 +2,11 @@ package config
import (
"os"
"paraclub-ai-mailer/internal/logger"
"strings"
"time"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)
@@ -46,15 +49,49 @@ type LoggingConfig struct {
}
func Load(path string) (*Config, error) {
logger.WithField("path", path).Debug("Loading configuration file")
data, err := os.ReadFile(path)
if err != nil {
logger.WithError(err).Error("Failed to read configuration file")
return nil, err
}
logger.WithField("bytes", len(data)).Debug("Read configuration file")
var config Config
if err := yaml.Unmarshal(data, &config); err != nil {
logger.WithError(err).Error("Failed to parse YAML configuration")
return nil, err
}
// Resolve environment variables in configuration
if strings.HasPrefix(config.IMAP.Password, "${") && strings.HasSuffix(config.IMAP.Password, "}") {
envVar := strings.TrimSuffix(strings.TrimPrefix(config.IMAP.Password, "${"), "}")
config.IMAP.Password = os.Getenv(envVar)
logger.WithField("envVar", envVar).Debug("Resolved IMAP password from environment")
}
if strings.HasPrefix(config.AI.OpenRouterAPIKey, "${") && strings.HasSuffix(config.AI.OpenRouterAPIKey, "}") {
envVar := strings.TrimSuffix(strings.TrimPrefix(config.AI.OpenRouterAPIKey, "${"), "}")
config.AI.OpenRouterAPIKey = os.Getenv(envVar)
logger.WithField("envVar", envVar).Debug("Resolved OpenRouter API key from environment")
}
logger.WithFields(logrus.Fields{
"imapServer": config.IMAP.Server,
"imapPort": config.IMAP.Port,
"imapUsername": config.IMAP.Username,
"imapMailboxIn": config.IMAP.MailboxIn,
"imapDraftBox": config.IMAP.DraftBox,
"imapUseTLS": config.IMAP.UseTLS,
"aiModel": config.AI.Model,
"aiTemperature": config.AI.Temperature,
"aiMaxTokens": config.AI.MaxTokens,
"contextUrlCount": len(config.Context.URLs),
"pollingInterval": config.Polling.Interval,
"loggingLevel": config.Logging.Level,
"loggingFilePath": config.Logging.FilePath,
}).Debug("Configuration loaded successfully")
return &config, nil
}