axe/internal/logging/logging.go
2026-10-18 22:07:25 +03:00

45 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package logging настраивает структурное логирование через log/slog.
//
// Логгер ставится дефолтным, чтобы пакеты писали slog.Info(...) без
// протаскивания логгера через все сигнатуры — в Go это принятое решение.
package logging
import (
"log/slog"
"os"
"strings"
)
// Setup создаёт корневой логгер и делает его дефолтным.
//
// LOG_LEVEL — debug | info | warn | error (по умолчанию info);
// LOG_FORMAT — text | json (по умолчанию text: читаемо в консоли,
// json выбирают, когда логи собирает агрегатор).
func Setup() *slog.Logger {
opts := &slog.HandlerOptions{Level: levelFromEnv()}
var handler slog.Handler
if strings.EqualFold(strings.TrimSpace(os.Getenv("LOG_FORMAT")), "json") {
handler = slog.NewJSONHandler(os.Stdout, opts)
} else {
handler = slog.NewTextHandler(os.Stdout, opts)
}
logger := slog.New(handler)
slog.SetDefault(logger)
return logger
}
func levelFromEnv() slog.Level {
switch strings.ToLower(strings.TrimSpace(os.Getenv("LOG_LEVEL"))) {
case "debug":
return slog.LevelDebug
case "warn", "warning":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.LevelInfo
}
}