- build: add makefile, dockerfile, ci and development stack - feat(config): add environment configuration and logger - feat(server): add server lifecycle with health and version routes - feat(db): add connection, contract check, migrations and stores - feat(cli): add command dispatch and user management - test(db): add integration tests against mysql
110 lines
2.2 KiB
Go
110 lines
2.2 KiB
Go
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"strings"
|
|
)
|
|
|
|
const LevelTrace = slog.Level(-8)
|
|
|
|
var errInvalidLogLevel = errors.New("invalid log level")
|
|
|
|
var logLevelNames = []struct {
|
|
level slog.Level
|
|
name string
|
|
}{
|
|
{slog.LevelError, "ERROR"},
|
|
{slog.LevelWarn, "WARN"},
|
|
{slog.LevelInfo, "INFO"},
|
|
{slog.LevelDebug, "DEBUG"},
|
|
{LevelTrace, "TRACE"},
|
|
}
|
|
|
|
var redactedLogKeys = map[string]bool{
|
|
"password": true,
|
|
"db_password": true,
|
|
"password_hash": true,
|
|
"token": true,
|
|
"session_token": true,
|
|
"cookie": true,
|
|
"dsn": true,
|
|
"secret": true,
|
|
}
|
|
|
|
const redactedLogValue = "[redacted]"
|
|
|
|
func parseLogLevel(s string) (slog.Level, error) {
|
|
for _, l := range logLevelNames {
|
|
if strings.EqualFold(s, l.name) && isASCII(s) {
|
|
return l.level, nil
|
|
}
|
|
}
|
|
return 0, errInvalidLogLevel
|
|
}
|
|
|
|
func logLevelName(level slog.Level) string {
|
|
for _, l := range logLevelNames {
|
|
if l.level == level {
|
|
return l.name
|
|
}
|
|
}
|
|
return level.String()
|
|
}
|
|
|
|
func newLogger(w io.Writer, level slog.Level) *slog.Logger {
|
|
return slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{
|
|
Level: level,
|
|
ReplaceAttr: replaceLogAttr,
|
|
}))
|
|
}
|
|
|
|
func replaceLogAttr(groups []string, a slog.Attr) slog.Attr {
|
|
if redactedLogKeys[strings.ToLower(a.Key)] {
|
|
return slog.String(a.Key, redactedLogValue)
|
|
}
|
|
if len(groups) != 0 {
|
|
return a
|
|
}
|
|
switch a.Key {
|
|
case slog.LevelKey:
|
|
if level, ok := a.Value.Any().(slog.Level); ok {
|
|
a.Value = slog.StringValue(logLevelName(level))
|
|
}
|
|
case slog.TimeKey:
|
|
if a.Value.Kind() == slog.KindTime {
|
|
a.Value = slog.TimeValue(a.Value.Time().UTC())
|
|
}
|
|
}
|
|
return a
|
|
}
|
|
|
|
func logTrace(ctx context.Context, log *slog.Logger, msg string, args ...any) {
|
|
log.Log(ctx, LevelTrace, msg, args...)
|
|
}
|
|
|
|
func traceFunc(ctx context.Context, log *slog.Logger, fn string) func() {
|
|
logTrace(ctx, log, "function entry", "func", fn)
|
|
return func() {
|
|
logTrace(ctx, log, "function exit", "func", fn)
|
|
}
|
|
}
|
|
|
|
func discardLogger() *slog.Logger {
|
|
return slog.New(slog.DiscardHandler)
|
|
}
|
|
|
|
func isASCII(s string) bool {
|
|
for i := 0; i < len(s); i++ {
|
|
if s[i] >= 0x80 {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|