Let logger work without file access

This commit is contained in:
Andrew-71 2024-03-23 16:17:06 +03:00
parent 8a571dbee8
commit 94952b5766

View file

@ -2,7 +2,6 @@ package main
import ( import (
"io" "io"
"log"
"log/slog" "log/slog"
"os" "os"
) )
@ -13,11 +12,11 @@ var LogFile = "config/log.txt"
func LogInit() { func LogInit() {
f, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) f, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil { if err != nil {
log.Fatalf("error opening log file: %v", err) slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, nil))) // Fallback to stdout
slog.Error("error opening log file, logging to stdout", "path", LogFile, "error", err)
return
} }
// No defer f.Close() because that breaks the MultiWriter // No defer f.Close() because that breaks the MultiWriter
w := io.MultiWriter(f, os.Stdout) w := io.MultiWriter(f, os.Stdout)
slog.SetDefault(slog.New(slog.NewTextHandler(w, nil))) slog.SetDefault(slog.New(slog.NewTextHandler(w, nil)))
} }