/
bi01
/
hashing_service
Обзор
Документация
Войти
/
bi01
/
hashing_service
Код
Пакеты
0
Релизы
0
Аналитика
Безопасность
develop
pkg/logging/logger.go
75 строк
2 KB
Oleg Biryukov
Init commit
14 июл 2024, 17:40
14 июл 2024, 17:40
de15ac0
Код
Авторство
О чём код?
package logging import ( "log/slog" "os" ) type Config struct { Environment string AppName string Debug bool } const ( LevelTrace = slog.Level(-8) LevelDebug = slog.LevelDebug LevelInfo = slog.LevelInfo LevelNotice = slog.Level(2) LevelWarning = slog.LevelWarn LevelError = slog.LevelError LevelEmergency = slog.Level(12) ) // InitLogger Initialize log/slog logger with custom settings. func InitLogger(conf Config) { var slogLevel slog.Level switch conf.Debug { case false: slogLevel = LevelInfo default: slogLevel = LevelTrace } slogOpts := slog.HandlerOptions{ AddSource: true, Level: slogLevel, ReplaceAttr: slogReplace, } logger := slog.New(slog.NewJSONHandler(os.Stdout, &slogOpts)) slog.SetDefault(logger) } // slogReplace Change default field: level, time. func slogReplace(_ []string, attr slog.Attr) slog.Attr { if attr.Key == slog.TimeKey { attr.Value = slog.StringValue(attr.Value.Time().Format("2006-01-02 15:04:05.000")) } if attr.Key == slog.LevelKey { // Handle custom level values. level := attr.Value.Any().(slog.Level) switch { case level < LevelDebug: attr.Value = slog.StringValue("TRACE") case level < LevelInfo: attr.Value = slog.StringValue("DEBUG") case level < LevelNotice: attr.Value = slog.StringValue("INFO") case level < LevelWarning: attr.Value = slog.StringValue("NOTICE") case level < LevelError: attr.Value = slog.StringValue("WARNING") case level < LevelEmergency: attr.Value = slog.StringValue("ERROR") default: attr.Value = slog.StringValue("EMERGENCY") } } return attr }