Make logging to file optional

This commit is contained in:
Andrew-71 2024-03-28 11:22:37 +03:00
parent 6449a300a4
commit 6e1095019f
4 changed files with 27 additions and 16 deletions

View file

@ -1,8 +1,7 @@
# TODO
List of things to add to this project
* Make scram configurable
* Use reflection in config loading
* Improve config and use reflection when loading it
* Check export function for improvements
* Add notes to frontend?
* More slog.Debug and a debug flag?

View file

@ -14,10 +14,11 @@ import (
var ConfigFile = "config/config.txt"
type Config struct {
Username string `config:"username"`
Password string `config:"password"`
Port int `config:"port"`
Scram bool `config:"enable_scram"`
Username string `config:"username"`
Password string `config:"password"`
Port int `config:"port"`
LogToFile bool `config:"log_to_file"`
Scram bool `config:"enable_scram"`
TelegramToken string `config:"tg_token"`
TelegramChat string `config:"tg_chat"`
@ -87,6 +88,12 @@ func (c *Config) Reload() error {
} else {
c.Scram = false
}
} else if key == "log_to_file" {
if value == "true" {
c.LogToFile = true
} else {
c.LogToFile = false
}
}
}
if err := scanner.Err(); err != nil {

View file

@ -1,4 +1,5 @@
username=admin
password=admin
port=7101
log_to_file=false
enable_scram=false

View file

@ -10,18 +10,22 @@ import (
var LogFile = "config/log.txt"
// LogInit makes slog output to both stdout and a file
// LogInit makes slog output to both stdout and a file if needed
func LogInit() {
f, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
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
var w io.Writer
if Cfg.LogToFile {
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", "path", LogFile, "error", err)
return
}
// No defer f.Close() because that breaks the MultiWriter
w = io.MultiWriter(f, os.Stdout)
} else {
w = os.Stdout
}
// No defer f.Close() because that breaks the MultiWriter
w := io.MultiWriter(f, os.Stdout)
slog.SetDefault(slog.New(slog.NewTextHandler(w, nil)))
// Make chi log to file too
// Make slog and chi use intended format
slog.SetDefault(slog.New(slog.NewTextHandler(w, nil)))
middleware.DefaultLogger = middleware.RequestLogger(&middleware.DefaultLogFormatter{Logger: log.Default(), NoColor: true})
}