hibiscus/internal/logging/logger.go

52 lines
1.5 KiB
Go
Raw Normal View History

2024-10-21 16:46:25 +03:00
package logging
2024-03-20 16:18:23 +03:00
import (
"io"
2024-03-26 18:42:41 +03:00
"log"
2024-03-20 16:18:23 +03:00
"log/slog"
"os"
2024-10-23 11:26:35 +03:00
"path"
"time"
2024-10-21 16:46:25 +03:00
"git.a71.su/Andrew71/hibiscus-txt/internal/config"
"github.com/go-chi/chi/v5/middleware"
2024-03-20 16:18:23 +03:00
)
2024-05-04 14:29:49 +03:00
var DebugMode = false
2024-03-20 16:18:23 +03:00
2024-10-23 14:11:02 +03:00
// file returns the appropriate filename for log
2024-10-23 11:26:35 +03:00
// (log_dir/hibiscus_YYYY-MM-DD_HH:MM:SS.log)
2024-10-23 14:11:02 +03:00
func file() string {
2024-10-23 11:26:35 +03:00
return config.Cfg.LogDir + "/hibiscus_" + time.Now().In(config.Cfg.Timezone).Format("2006-01-02_15:04:05") + ".log"
}
// 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-10-23 14:11:02 +03:00
logFile := file()
2024-10-23 11:26:35 +03:00
var w io.Writer = os.Stdout
2024-10-21 16:46:25 +03:00
if config.Cfg.LogToFile {
2024-10-23 11:26:35 +03:00
// Create dir in case it doesn't exist yet to avoid errors
err := os.MkdirAll(path.Dir(logFile), 0755)
2024-03-28 11:22:37 +03:00
if err != nil {
2024-10-23 11:26:35 +03:00
slog.Error("error creating log dir, logging to stdout only", "path", path.Dir(logFile), "error", err)
} else {
f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
slog.Error("error opening log file, logging to stdout only", "path", logFile, "error", err)
return
}
// No defer f.Close() because that breaks the MultiWriter
w = io.MultiWriter(f, os.Stdout)
2024-03-28 11:22:37 +03:00
}
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-10-23 14:11:02 +03:00
slog.Debug("Debug mode enabled") // This string is only shown if debugging
2024-03-20 16:18:23 +03:00
}