hibiscus/logger.go

36 lines
937 B
Go
Raw Normal View History

2024-03-20 16:18:23 +03:00
package main
import (
2024-03-26 18:42:41 +03:00
"github.com/go-chi/chi/v5/middleware"
2024-03-20 16:18:23 +03:00
"io"
2024-03-26 18:42:41 +03:00
"log"
2024-03-20 16:18:23 +03:00
"log/slog"
"os"
)
2024-05-04 14:29:49 +03:00
var DebugMode = false
2024-03-20 16:18:23 +03:00
// LogInit makes slog output to both os.Stdout and a file if needed, and sets slog.LevelDebug if enabled.
2024-03-20 16:18:23 +03:00
func LogInit() {
2024-03-28 11:22:37 +03:00
var w io.Writer
if Cfg.LogToFile {
2024-05-04 15:39:15 +03:00
f, err := os.OpenFile(Cfg.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
2024-03-28 11:22:37 +03:00
if err != nil {
2024-05-04 15:39:15 +03:00
slog.Error("error opening log file, logging to stdout", "path", Cfg.LogFile, "error", err)
2024-03-28 11:22:37 +03:00
return
}
// No defer f.Close() because that breaks the MultiWriter
w = io.MultiWriter(f, os.Stdout)
} else {
w = os.Stdout
2024-03-20 16:18:23 +03:00
}
2024-03-26 18:42:41 +03:00
2024-03-28 11:22:37 +03:00
// Make slog and chi use intended format
2024-05-04 14:29:49 +03:00
var opts *slog.HandlerOptions
if DebugMode {
opts = &slog.HandlerOptions{Level: slog.LevelDebug}
}
slog.SetDefault(slog.New(slog.NewTextHandler(w, opts)))
2024-03-26 18:42:41 +03:00
middleware.DefaultLogger = middleware.RequestLogger(&middleware.DefaultLogFormatter{Logger: log.Default(), NoColor: true})
2024-03-20 16:18:23 +03:00
}