aboutsummaryrefslogtreecommitdiffstats
path: root/backend/internal
diff options
context:
space:
mode:
authorLibravatarLibravatar Biswa Kalyan Bhuyan <biswa@surgot.in> 2025-04-25 03:07:37 +0530
committerLibravatarLibravatar Biswa Kalyan Bhuyan <biswa@surgot.in> 2025-04-25 03:07:37 +0530
commit7b9fe4639cafbcc35c860e23a20a2c0d2e29283d (patch)
treeeef9b87745ed5e9b90f842c004941d12d705e7ac /backend/internal
parentd8856efd30dfcb05b26a5b66b5bb14cc0604e2b1 (diff)
downloadfinance-7b9fe4639cafbcc35c860e23a20a2c0d2e29283d.tar.gz
finance-7b9fe4639cafbcc35c860e23a20a2c0d2e29283d.tar.bz2
finance-7b9fe4639cafbcc35c860e23a20a2c0d2e29283d.zip
finance/backend: feat: set up logging and error handling
Diffstat (limited to 'backend/internal')
-rw-r--r--backend/internal/config/config.go88
-rw-r--r--backend/internal/logger/logger.go144
-rw-r--r--backend/internal/middleware/error_handler.go119
3 files changed, 317 insertions, 34 deletions
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index f61f423..f302827 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -1,54 +1,74 @@
package config
import (
- "log"
+ "fmt"
"os"
"github.com/joho/godotenv"
)
-// Config holds the application configuration
+// Config holds application configuration
type Config struct {
+ // Database configuration
DatabaseDSN string
- JWTSecret string // Secret key for signing JWTs
- // Add other config fields here later (e.g., server port)
+
+ // JWT configuration
+ JWTSecret string
+ JWTExpiry int // in hours
+
+ // Server configuration
+ ServerPort int
+ ServerHost string
+
+ // Environment (development, staging, production)
+ Environment string
}
-// LoadConfig loads configuration from environment variables or a .env file
+// LoadConfig loads the application configuration from environment variables
func LoadConfig() (*Config, error) {
- // Attempt to load .env file (useful for development)
- // In production, rely on environment variables set directly
- err := godotenv.Load() // Load .env file from current directory or parent dirs
- if err != nil {
- log.Println("No .env file found, relying on environment variables")
+ // Load .env file if it exists
+ _ = godotenv.Load() // Ignore error if .env file doesn't exist
+
+ // Set defaults and override with environment variables
+ config := &Config{
+ DatabaseDSN: getEnv("DATABASE_DSN", "postgresql://postgres:postgres@localhost:5432/finance?sslmode=disable"),
+ JWTSecret: getEnv("JWT_SECRET", "supersecretkey"), // This should be changed in production
+ JWTExpiry: getEnvInt("JWT_EXPIRY", 24), // Default to 24 hours
+ ServerPort: getEnvInt("SERVER_PORT", 8080), // Default to 8080
+ ServerHost: getEnv("SERVER_HOST", "0.0.0.0"), // Default to all interfaces
+ Environment: getEnv("APP_ENV", "development"), // Default to development
}
- dsn := os.Getenv("DATABASE_DSN")
- if dsn == "" {
- // Set a default for local development if not provided
- log.Println("DATABASE_DSN not set, using default local PostgreSQL DSN")
- log.Println("IMPORTANT: Ensure PostgreSQL is running with the correct credentials.")
- log.Println("Try creating a database 'finance' and setting up a user with the correct permissions.")
- log.Println("Example commands:")
- log.Println(" createdb finance")
- log.Println(" createuser -P -s -e user_name")
-
- // Use more common/generic default credentials
- dsn = "host=localhost user=postgres password=postgres dbname=finance port=5432 sslmode=disable TimeZone=UTC"
- // Consider making the default conditional or removing it for stricter environments
+ return config, nil
+}
+
+// getEnv gets an environment variable or returns a default value
+func getEnv(key, defaultValue string) string {
+ value := os.Getenv(key)
+ if value == "" {
+ return defaultValue
+ }
+ return value
+}
+
+// getEnvInt gets an environment variable as an integer or returns a default value
+func getEnvInt(key string, defaultValue int) int {
+ value := os.Getenv(key)
+ if value == "" {
+ return defaultValue
}
- jwtSecret := os.Getenv("JWT_SECRET")
- if jwtSecret == "" {
- log.Println("WARNING: JWT_SECRET environment variable not set. Using an insecure default.")
- // !!! IMPORTANT: Use a strong, randomly generated secret in production !!!
- // For development only:
- jwtSecret = "insecure-default-dev-secret-change-me"
- // return nil, errors.New("JWT_SECRET environment variable is required")
+ intValue, err := parseInt(value)
+ if err != nil {
+ return defaultValue
}
- return &Config{
- DatabaseDSN: dsn,
- JWTSecret: jwtSecret,
- }, nil
+ return intValue
+}
+
+// parseInt parses a string to an int
+func parseInt(value string) (int, error) {
+ intValue := 0
+ _, err := fmt.Sscanf(value, "%d", &intValue)
+ return intValue, err
}
diff --git a/backend/internal/logger/logger.go b/backend/internal/logger/logger.go
new file mode 100644
index 0000000..7de276d
--- /dev/null
+++ b/backend/internal/logger/logger.go
@@ -0,0 +1,144 @@
+package logger
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "time"
+)
+
+// LogLevel represents the severity of a log message
+type LogLevel int
+
+const (
+ // DEBUG level for detailed information
+ DEBUG LogLevel = iota
+ // INFO level for general operational information
+ INFO
+ // WARN level for warnings
+ WARN
+ // ERROR level for errors
+ ERROR
+ // FATAL level for fatal errors that cause the application to exit
+ FATAL
+)
+
+var (
+ // defaultLogger is the default logger used by the package
+ defaultLogger *Logger
+ // level names for pretty printing
+ levelNames = []string{
+ "DEBUG",
+ "INFO",
+ "WARN",
+ "ERROR",
+ "FATAL",
+ }
+)
+
+// Logger is a custom logger that wraps the standard log package
+type Logger struct {
+ debugLog *log.Logger
+ infoLog *log.Logger
+ warnLog *log.Logger
+ errorLog *log.Logger
+ fatalLog *log.Logger
+}
+
+// Init initializes the default logger with the specified output and minimum log level
+func Init(out io.Writer, level LogLevel) {
+ defaultLogger = NewLogger(out, level)
+}
+
+// NewLogger creates a new logger with the specified output and minimum log level
+func NewLogger(out io.Writer, level LogLevel) *Logger {
+ if out == nil {
+ out = os.Stdout
+ }
+
+ flags := log.Ldate | log.Ltime
+
+ l := &Logger{
+ debugLog: log.New(out, "[DEBUG] ", flags),
+ infoLog: log.New(out, "[INFO] ", flags),
+ warnLog: log.New(out, "[WARN] ", flags),
+ errorLog: log.New(out, "[ERROR] ", flags),
+ fatalLog: log.New(out, "[FATAL] ", flags),
+ }
+
+ return l
+}
+
+// Debug logs a debug message
+func (l *Logger) Debug(v ...interface{}) {
+ l.debugLog.Println(v...)
+}
+
+// Info logs an info message
+func (l *Logger) Info(v ...interface{}) {
+ l.infoLog.Println(v...)
+}
+
+// Warn logs a warning message
+func (l *Logger) Warn(v ...interface{}) {
+ l.warnLog.Println(v...)
+}
+
+// Error logs an error message
+func (l *Logger) Error(v ...interface{}) {
+ l.errorLog.Println(v...)
+}
+
+// Fatal logs a fatal message and exits the program
+func (l *Logger) Fatal(v ...interface{}) {
+ l.fatalLog.Println(v...)
+ os.Exit(1)
+}
+
+// Debugf logs a formatted debug message
+func (l *Logger) Debugf(format string, v ...interface{}) {
+ l.debugLog.Printf(format, v...)
+}
+
+// Infof logs a formatted info message
+func (l *Logger) Infof(format string, v ...interface{}) {
+ l.infoLog.Printf(format, v...)
+}
+
+// Warnf logs a formatted warning message
+func (l *Logger) Warnf(format string, v ...interface{}) {
+ l.warnLog.Printf(format, v...)
+}
+
+// Errorf logs a formatted error message
+func (l *Logger) Errorf(format string, v ...interface{}) {
+ l.errorLog.Printf(format, v...)
+}
+
+// Fatalf logs a formatted fatal message and exits the program
+func (l *Logger) Fatalf(format string, v ...interface{}) {
+ l.fatalLog.Printf(format, v...)
+ os.Exit(1)
+}
+
+// LogRequest logs an HTTP request
+func (l *Logger) LogRequest(method, path, ip, userAgent string, status int, latency time.Duration) {
+ l.Infof(
+ "Request: %s %s | Status: %d | IP: %s | User-Agent: %s | Latency: %v",
+ method, path, status, ip, userAgent, latency,
+ )
+}
+
+// GetTimestamp returns the current timestamp as a formatted string
+func GetTimestamp() string {
+ return time.Now().Format("2006-01-02 15:04:05")
+}
+
+// FormatRequestLog formats a request log entry with useful information
+func FormatRequestLog(method, path, ip, userAgent string, statusCode int, latency time.Duration) string {
+ return fmt.Sprintf(
+ "Request: %s %s | Status: %d | IP: %s | Latency: %s | User-Agent: %s",
+ method, path, statusCode, ip, latency, userAgent,
+ )
+}
diff --git a/backend/internal/middleware/error_handler.go b/backend/internal/middleware/error_handler.go
new file mode 100644
index 0000000..4e7eedf
--- /dev/null
+++ b/backend/internal/middleware/error_handler.go
@@ -0,0 +1,119 @@
+package middleware
+
+import (
+ "finance/backend/internal/logger"
+ "net/http"
+ "runtime/debug"
+ "time"
+
+ "github.com/gin-gonic/gin"
+)
+
+// ErrorResponse represents a standardized error response
+type ErrorResponse struct {
+ Status int `json:"status"`
+ Message string `json:"message"`
+ Error string `json:"error,omitempty"`
+}
+
+// ErrorHandler middleware recovers from panics and logs errors
+func ErrorHandler() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ defer func() {
+ if err := recover(); err != nil {
+ // Get logger from the context or create a new one
+ log := getLoggerFromContext(c)
+
+ // Log the stack trace
+ log.Errorf("PANIC RECOVERED: %v\n%s", err, debug.Stack())
+
+ // Return a 500 Internal Server Error response
+ c.JSON(http.StatusInternalServerError, ErrorResponse{
+ Status: http.StatusInternalServerError,
+ Message: "An unexpected error occurred",
+ })
+
+ // Abort the request
+ c.Abort()
+ }
+ }()
+
+ c.Next()
+ }
+}
+
+// RequestLogger middleware logs information about each request
+func RequestLogger(log *logger.Logger) gin.HandlerFunc {
+ return func(c *gin.Context) {
+ // Store logger in context for other middleware to use
+ c.Set("logger", log)
+
+ // Start timer
+ startTime := time.Now()
+
+ // Process request
+ c.Next()
+
+ // Calculate latency
+ latency := time.Since(startTime)
+
+ // Get request details
+ method := c.Request.Method
+ path := c.Request.URL.Path
+ statusCode := c.Writer.Status()
+ ip := c.ClientIP()
+ userAgent := c.Request.UserAgent()
+
+ // Log request info based on status code
+ logMessage := logger.FormatRequestLog(method, path, ip, userAgent, statusCode, latency)
+
+ if statusCode >= 500 {
+ log.Error(logMessage)
+ } else if statusCode >= 400 {
+ log.Warn(logMessage)
+ } else {
+ log.Info(logMessage)
+ }
+ }
+}
+
+// NotFoundHandler handles 404 errors
+func NotFoundHandler() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ // Get logger from the context or create a new one
+ log := getLoggerFromContext(c)
+
+ log.Warnf("404 Not Found: %s %s", c.Request.Method, c.Request.URL.Path)
+ c.JSON(http.StatusNotFound, ErrorResponse{
+ Status: http.StatusNotFound,
+ Message: "The requested resource was not found",
+ })
+ }
+}
+
+// MethodNotAllowedHandler handles 405 errors
+func MethodNotAllowedHandler() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ // Get logger from the context or create a new one
+ log := getLoggerFromContext(c)
+
+ log.Warnf("405 Method Not Allowed: %s %s", c.Request.Method, c.Request.URL.Path)
+ c.JSON(http.StatusMethodNotAllowed, ErrorResponse{
+ Status: http.StatusMethodNotAllowed,
+ Message: "The requested method is not allowed",
+ })
+ }
+}
+
+// getLoggerFromContext retrieves the logger from context or creates a default one
+func getLoggerFromContext(c *gin.Context) *logger.Logger {
+ loggerInterface, exists := c.Get("logger")
+ if exists {
+ if log, ok := loggerInterface.(*logger.Logger); ok {
+ return log
+ }
+ }
+
+ // If no logger in context, create a new one
+ return logger.NewLogger(nil, logger.INFO)
+}