Start adding some logging

This commit is contained in:
Carl Pearson
2024-09-21 06:22:34 -06:00
parent 62d9ebf74b
commit dc04468f7c
6 changed files with 72 additions and 13 deletions

1
go.mod
View File

@@ -8,6 +8,7 @@ require (
github.com/google/uuid v1.6.0
github.com/gorilla/sessions v1.4.0
github.com/labstack/echo/v4 v4.10.2
github.com/sirupsen/logrus v1.9.3
golang.org/x/crypto v0.9.0
gorm.io/driver/sqlite v1.5.1
gorm.io/gorm v1.25.1

View File

@@ -51,17 +51,28 @@ func registerPostHandler(c echo.Context) error {
return c.Redirect(http.StatusSeeOther, "/login")
}
func loginHandler(c echo.Context) error {
return c.Render(http.StatusOK, "login.html", nil)
}
func homeHandler(c echo.Context) error {
// redirect to /videos if logged in
session, err := store.Get(c.Request(), "session")
if err == nil {
_, ok := session.Values["user_id"]
if ok {
fmt.Println("homeHandler: session contains user_id. Redirect to /video")
return c.Redirect(http.StatusSeeOther, "/videos")
}
}
return c.Render(http.StatusOK, "home.html",
map[string]interface{}{
"Footer": makeFooter(),
})
}
func loginHandler(c echo.Context) error {
return c.Render(http.StatusOK, "login.html", nil)
}
func loginPostHandler(c echo.Context) error {
username := c.FormValue("username")
password := c.FormValue("password")

28
logger.go Normal file
View File

@@ -0,0 +1,28 @@
package main
import (
"fmt"
"os"
"path"
"runtime"
"github.com/sirupsen/logrus"
)
var log *logrus.Logger
func initLogger() {
log = logrus.New()
log.SetOutput(os.Stdout)
log.SetLevel(logrus.DebugLevel)
log.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
filename := path.Base(f.File)
return "", fmt.Sprintf("%s:%d", filename, f.Line)
},
})
log.SetReportCaller(true)
}

29
main.go
View File

@@ -4,14 +4,17 @@ import (
"fmt"
"html/template"
"io"
golog "log"
"os"
"path/filepath"
"time"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var db *gorm.DB
@@ -37,25 +40,41 @@ func ensureAdminAccount(db *gorm.DB) error {
func main() {
fmt.Printf("git SHA: %s\n", getGitSHA())
initLogger()
log.Infof("GitSHA: %s", getGitSHA())
log.Infof("BuildDate: %s", getBuildDate())
gormLogger := logger.New(
golog.New(os.Stdout, "\r\n", golog.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Warn, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
ParameterizedQueries: true, // Don't include params in the SQL log
Colorful: false, // Disable color
},
)
// Create config database
err := os.MkdirAll(getConfigDir(), 0700)
if err != nil {
panic("failed to create config dir")
log.Panicf("failed to create config dir %s", getConfigDir())
}
// Initialize database
dbPath := filepath.Join(getConfigDir(), "videos.db")
db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{
Logger: gormLogger,
})
if err != nil {
panic("failed to connect database")
log.Panicf("failed to connect to database %s", dbPath)
}
// set only a single connection so we don't actually have concurrent writes
sqlDB, err := db.DB()
if err != nil {
panic("failed to retrieve database")
log.Panicln("failed to retrieve database")
}
sqlDB.SetMaxOpenConns(1)

View File

@@ -159,7 +159,7 @@ func CreateTempURL(filePath string) (TempURL, error) {
}
func cleanupExpiredURLs() {
fmt.Println("cleanupExpiredURLs...")
log.Debugln("cleanupExpiredURLs...")
result := db.Unscoped().Where("expires_at < ?", time.Now()).Delete(&TempURL{})
if result.Error != nil {
fmt.Printf("Error cleaning up expired URLs: %v\n", result.Error)
@@ -170,7 +170,7 @@ func cleanupExpiredURLs() {
func vacuumDatabase() {
if err := db.Exec("VACUUM").Error; err != nil {
fmt.Println(err)
log.Errorln(err)
}
}

View File

@@ -208,7 +208,7 @@ func audioToAudio(transID uint, kbps uint, srcFilepath string) {
}
func transcodePending() {
fmt.Println("transcodePending...")
log.Debugln("transcodePending...")
// any running jobs here got stuck or dead in the midde, so reset them
db.Model(&Transcode{}).Where("status = ?", "running").Update("status", "pending")
@@ -223,7 +223,7 @@ func transcodePending() {
"ELSE 1 END").First(&trans).Error
// err := db.First(&trans, "status = ?", "pending").Error
if err == gorm.ErrRecordNotFound {
fmt.Println("no pending transcode jobs")
log.Debugln("no pending transcode jobs")
break // no more pending jobs
}