Logging: structured slog messages throughout, and WithLogger options so callers choose the logger
Log messages are lower-case event names with their details as key/value
attributes ("error" for errors), in place of formatted strings.
Loggable package take a WithLogger option as part of their "New*" call,
defaulting to slog.Default(). Each tags its lines with its `component`.
Some debug loggers print directly rather than using slog when in
terminal logging mode.
This commit is contained in:
1 parent
0b5fde9563
commit
043e307663
49 files changed
+598
-248
No files matched your search
@@ -70,11 +70,11 @@ func LoadFromViper(conf *JobSearchConfig) {
|
||||
}
|
||||
value, ok := viperValue(key, keyType)
|
||||
if !ok {
|
||||
slog.Error(fmt.Sprintf("unknown key type: %s", keyType))
|
||||
slog.Error("unknown config key type", "key", key, "kind", keyType.String())
|
||||
continue
|
||||
}
|
||||
if err := conf.SetValue(key, value); err != nil {
|
||||
slog.Warn("ignoring invalid config value", "key", key, "err", err)
|
||||
slog.Warn("ignoring invalid config value", "key", key, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+62
-21
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
@@ -9,41 +10,81 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/logging"
|
||||
)
|
||||
|
||||
// printEnv logs the JOBSEARCH* environment variables at debug level.
|
||||
// printEnv logs each JOBSEARCH* environment variable at debug level. On a
|
||||
// terminal it logs one line and prints the variables under it as
|
||||
// "name=value" lines; elsewhere each variable is a log entry of its own.
|
||||
func printEnv() {
|
||||
slog.Debug("Environment:")
|
||||
env := os.Environ()
|
||||
slices.Sort(env)
|
||||
for _, e := range env {
|
||||
pair := strings.SplitN(e, "=", 2)
|
||||
if strings.HasPrefix(pair[0], EnvPrefix) {
|
||||
slog.Debug("\t" + pair[0] + "=" + pair[1])
|
||||
logger := slog.Default()
|
||||
terminal := logging.WritesToTerminal(logger.Handler())
|
||||
if terminal && !logger.Enabled(context.Background(), slog.LevelDebug) {
|
||||
return
|
||||
}
|
||||
|
||||
var variables []string
|
||||
for _, variable := range os.Environ() {
|
||||
if strings.HasPrefix(variable, EnvPrefix) {
|
||||
variables = append(variables, variable)
|
||||
}
|
||||
}
|
||||
slices.Sort(variables)
|
||||
|
||||
if terminal {
|
||||
logger.Debug("environment variables", "count", len(variables))
|
||||
}
|
||||
for _, variable := range variables {
|
||||
if terminal {
|
||||
logging.PrintToTerminal("\t" + variable)
|
||||
continue
|
||||
}
|
||||
name, value, _ := strings.Cut(variable, "=")
|
||||
logger.Debug("environment variable", "name", name, "value", value)
|
||||
}
|
||||
}
|
||||
|
||||
// printLoadedConfig logs every key set by the config file or an environment
|
||||
// variable (see isExplicitlySet), with its value and type, at debug level.
|
||||
// variable (see isExplicitlySet), with its value and type, at debug level. On
|
||||
// a terminal it logs one line and prints the values under it as
|
||||
// "key = value <type>" lines; elsewhere each value is a log entry of its own.
|
||||
func printLoadedConfig() {
|
||||
slog.Debug("Loaded config:")
|
||||
keys := viper.AllKeys()
|
||||
for i := range keys {
|
||||
k := keys[i]
|
||||
if isExplicitlySet(k) {
|
||||
v := viper.Get(k)
|
||||
t := reflect.TypeOf(v)
|
||||
slog.Debug(
|
||||
"\t" + k + " = " + fmt.Sprintf("%#v", v) +
|
||||
" <" + t.Kind().String() + ">",
|
||||
)
|
||||
logger := slog.Default()
|
||||
terminal := logging.WritesToTerminal(logger.Handler())
|
||||
if terminal && !logger.Enabled(context.Background(), slog.LevelDebug) {
|
||||
return
|
||||
}
|
||||
|
||||
var keys []string
|
||||
for _, key := range viper.AllKeys() {
|
||||
if isExplicitlySet(key) {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
|
||||
if terminal {
|
||||
logger.Debug("loaded config values", "count", len(keys))
|
||||
}
|
||||
for _, key := range keys {
|
||||
value := viper.Get(key)
|
||||
kind := reflect.TypeOf(value).Kind().String()
|
||||
if terminal {
|
||||
logging.PrintToTerminal(
|
||||
fmt.Sprintf("\t%s = %#v <%s>", key, value, kind),
|
||||
)
|
||||
continue
|
||||
}
|
||||
logger.Debug(
|
||||
"loaded config value",
|
||||
"key", key,
|
||||
"value", value,
|
||||
"type", kind,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// printConfig logs conf at debug level.
|
||||
func printConfig(conf JobSearchConfig) {
|
||||
slog.Debug("Config:")
|
||||
conf.PrintLog(slog.LevelDebug)
|
||||
}
|
||||
@@ -68,14 +68,14 @@ func loadConfig(cfgFile string) error {
|
||||
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
|
||||
// Indicates an explicitly set config file is not found or
|
||||
// that no config file was found in any search path
|
||||
slog.Warn("No config file found!")
|
||||
slog.Warn("no config file found; using defaults")
|
||||
} else {
|
||||
// Config file was found but another error was produced
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// Config file found and successfully parsed
|
||||
slog.Info("Using config file: " + viper.ConfigFileUsed())
|
||||
slog.Info("using config file", "file", viper.ConfigFileUsed())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ func TestInitNoConfigFile(t *testing.T) {
|
||||
if err := Init("", &conf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "No config file found") {
|
||||
if !strings.Contains(logs.String(), "no config file found") {
|
||||
t.Errorf("no warning logged: %s", logs)
|
||||
}
|
||||
if conf.Logging.Level != "warn" {
|
||||
@@ -116,7 +116,7 @@ func TestInitKeepsCommandLineLevel(t *testing.T) {
|
||||
t.Errorf("Logging.Level = %q; want %s kept", conf.Logging.Level, level)
|
||||
}
|
||||
// At debug, the environment and loaded config are logged.
|
||||
gotDebug := strings.Contains(logs.String(), "Loaded config:")
|
||||
gotDebug := strings.Contains(logs.String(), "loaded config value")
|
||||
if gotDebug != (level == "debug") {
|
||||
t.Errorf("debug output logged = %v at level %s: %s", gotDebug, level, logs)
|
||||
}
|
||||
@@ -241,9 +241,9 @@ func TestPrintLoadedConfig(t *testing.T) {
|
||||
|
||||
out := logs.String()
|
||||
for _, want := range []string{
|
||||
`logging.level = \"info\" <string>`,
|
||||
`server.websocket.connection_limit.enabled = true <bool>`,
|
||||
`database.file = \"/tmp/js.db\" <string>`,
|
||||
`key=logging.level value=info type=string`,
|
||||
`key=server.websocket.connection_limit.enabled value=true type=bool`,
|
||||
`key=database.file value=/tmp/js.db type=string`,
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("missing %q in:\n%s", want, out)
|
||||
|
||||
+25
-20
@@ -1,10 +1,13 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"slices"
|
||||
|
||||
"git.avsdev.uk/Go/job-search/internal/logging"
|
||||
)
|
||||
|
||||
// PrintTerminal prints the configuration to stdout as String formats it.
|
||||
@@ -23,31 +26,33 @@ func (conf JobSearchConfig) PrintYaml() {
|
||||
}
|
||||
|
||||
// PrintLog logs each configuration key and value, sorted by key, at atLevel:
|
||||
// debug, warn, error, or info for any other level.
|
||||
// debug, warn, error, or info for any other level. On a terminal it logs one
|
||||
// line and prints the values under it as "key = value" lines; elsewhere each
|
||||
// value is a log entry of its own.
|
||||
func (conf JobSearchConfig) PrintLog(atLevel slog.Level) {
|
||||
var logFn func(args ...interface{})
|
||||
|
||||
switch atLevel {
|
||||
case slog.LevelDebug:
|
||||
logFn = func(args ...interface{}) {
|
||||
slog.Debug(fmt.Sprint(args...))
|
||||
}
|
||||
case slog.LevelError:
|
||||
logFn = func(args ...interface{}) {
|
||||
slog.Error(fmt.Sprint(args...))
|
||||
}
|
||||
case slog.LevelWarn:
|
||||
logFn = func(args ...interface{}) {
|
||||
slog.Warn(fmt.Sprint(args...))
|
||||
}
|
||||
case slog.LevelDebug, slog.LevelWarn, slog.LevelError:
|
||||
default:
|
||||
logFn = func(args ...interface{}) {
|
||||
slog.Info(fmt.Sprint(args...))
|
||||
}
|
||||
atLevel = slog.LevelInfo
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
logger := slog.Default()
|
||||
flat := conf.Flatten()
|
||||
for _, k := range slices.Sorted(maps.Keys(flat)) {
|
||||
logFn("\t", k, " = ", flat[k])
|
||||
keys := slices.Sorted(maps.Keys(flat))
|
||||
|
||||
if logging.WritesToTerminal(logger.Handler()) {
|
||||
if !logger.Enabled(ctx, atLevel) {
|
||||
return
|
||||
}
|
||||
logger.Log(ctx, atLevel, "config values", "count", len(keys))
|
||||
for _, key := range keys {
|
||||
logging.PrintToTerminal(fmt.Sprintf("\t%s = %v", key, flat[key]))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
for _, key := range keys {
|
||||
logger.Log(ctx, atLevel, "config value", "key", key, "value", flat[key])
|
||||
}
|
||||
}
|
||||
@@ -108,15 +108,15 @@ func TestPrintLog(t *testing.T) {
|
||||
t.Errorf("PrintLog(%v) line %q; want %s", tt.at, l, tt.want)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(logs.String(), "logging.level = warn") {
|
||||
if !strings.Contains(logs.String(), "key=logging.level value=warn") {
|
||||
t.Errorf("PrintLog(%v) missing logging.level:\n%s", tt.at, logs)
|
||||
}
|
||||
// Each line is msg="\t<key> = <value>".
|
||||
// Each line is msg="config value" key=<key> value=<value>.
|
||||
flat := conf.Flatten()
|
||||
var keys []string
|
||||
for _, l := range lines {
|
||||
_, msg, _ := strings.Cut(l, `msg="\t`)
|
||||
key, _, _ := strings.Cut(msg, " = ")
|
||||
_, rest, _ := strings.Cut(l, ` key=`)
|
||||
key, _, _ := strings.Cut(rest, " ")
|
||||
if _, ok := flat[key]; !ok {
|
||||
t.Errorf("PrintLog(%v) line %q: no key", tt.at, l)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user