Clean up error handling, begin migration to log/slog

This commit is contained in:
Maximilian 2023-08-17 21:13:17 -05:00
parent 1d400efa19
commit ee4c9f9199

29
main.go
View File

@ -9,7 +9,7 @@ import (
"context"
"embed"
"errors"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
@ -34,23 +34,26 @@ func main() {
if _, err := os.Stat("logs"); os.IsNotExist(err) {
err := os.Mkdir("logs", 0755)
if err != nil {
log.Println("Failed to create log directory")
log.Println(err)
return
panic("Failed to create log directory: " + err.Error())
}
}
// Create log file and set output
file, err := os.OpenFile("logs/"+time.Now().Format("2006-01-02")+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
log.SetOutput(file)
file, err := os.OpenFile("logs/"+time.Now().Format("2006-01-02")+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
panic("Error creating log file: " + err.Error())
}
logger := slog.New(slog.NewTextHandler(file, nil))
slog.SetDefault(logger) // Set structured logger globally
// Connect to database and run migrations
appLoaded.Db = database.Connect(&appLoaded)
if appLoaded.Config.Db.AutoMigrate {
err = models.RunAllMigrations(&appLoaded)
if err != nil {
log.Println(err)
return
slog.Error("error running migrations: " + err.Error())
os.Exit(1)
}
}
@ -67,10 +70,11 @@ func main() {
// Start server
server := &http.Server{Addr: appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port}
go func() {
log.Println("Starting server and listening on " + appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port)
slog.Info("Starting server and listening on " + appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port)
err := server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Could not listen on %s: %v\n", appLoaded.Config.Listen.Ip+":"+appLoaded.Config.Listen.Port, err)
slog.Error("Could not listen on %s: %v\n", appLoaded.Config.Listen.Ip+":"+appLoaded.Config.Listen.Port, err)
os.Exit(1)
}
}()
@ -81,10 +85,11 @@ func main() {
go app.RunScheduledTasks(&appLoaded, 100, stop)
<-interrupt
log.Println("Interrupt signal received. Shutting down server...")
slog.Info("Interrupt signal received. Shutting down server...")
err = server.Shutdown(context.Background())
if err != nil {
log.Fatalf("Could not gracefully shutdown the server: %v\n", err)
slog.Error("Could not gracefully shutdown the server: %v\n", err)
os.Exit(1)
}
}