~bigbes/huntsman

huntsman/internal/platform/observability/logging.go -rw-r--r-- 1023 bytes
766fa805 — Eugene Blikh Add BSD 2-Clause license 6 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Package observability wires up logging.
package observability

import (
	"log/slog"
	"os"
	"strings"

	"go.bigb.es/auxilia/scribe"
)

// NewLogger builds a slog.Logger backed by an auxilia/scribe handler.
//
// "human" produces a colorized TintHandler suitable for terminals; "json"
// produces a structured handler suitable for log aggregators. Unknown
// formats fall back to "human" so a typo doesn't break logging entirely.
func NewLogger(level, format string) *slog.Logger {
	lvl := parseLevel(level)
	opts := []scribe.Option{
		scribe.WithWriter(os.Stdout),
		scribe.WithLevel(lvl),
	}

	var handler slog.Handler
	if strings.EqualFold(format, "json") {
		handler = scribe.NewJSONHandler(opts...)
	} else {
		handler = scribe.NewTintHandler(opts...)
	}
	return slog.New(handler)
}

func parseLevel(level string) slog.Level {
	switch strings.ToLower(level) {
	case "debug":
		return slog.LevelDebug
	case "warn":
		return slog.LevelWarn
	case "error":
		return slog.LevelError
	default:
		return slog.LevelInfo
	}
}