refactor(log): split location into package/file/class/method, auto-derived

Per the log schema: 'package' is the Go package (absent on
Python-emitted lines), 'file' the Go/Python source basename, 'class' the
Go receiver or Python class (omitted when there is none -- free
functions no longer masquerade under a package-as-class), 'method' the
emitting function. applog.App() now takes no arguments and derives all
of it from runtime.Caller, so labels can never drift from the code; the
manual http/wrapper emitters and forwarded wrapper.py lines (file=
wrapper.py, no package) carry the same fields.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-04 19:59:48 +02:00
parent 6effb79097
commit 10cdc4176a
14 changed files with 91 additions and 47 deletions

View File

@@ -1,15 +1,18 @@
// Package applog provides geniusrun's structured JSON logging: a
// log/slog-based logger writing to stdout, plus the App helper that tags
// records with the mandatory schema fields every geniusrun log line
// carries -- "type" ("app" | "http" | "wrapper"), "class" (Go type with
// its package, or the package/module name for free functions), and
// "method" (the Go or Python function emitting the record). "msg" is
// optional: NewLogger's handler drops it when empty.
// records with the schema fields every geniusrun log line carries --
// "type" ("app" | "http" | "wrapper"), "package" (Go package; absent on
// Python-emitted lines), "file" (Go/Python source file basename), "class"
// (Go receiver type or Python class, omitted when there is none), and
// "method" (the emitting Go/Python function). "msg" is optional:
// NewLogger's handler drops it when empty.
package applog
import (
"io"
"log/slog"
"path/filepath"
"runtime"
"strings"
)
@@ -30,13 +33,44 @@ func NewLogger(level string, w io.Writer) *slog.Logger {
}))
}
// App returns the default logger tagged with the mandatory schema fields
// for an ordinary application record: type=app, plus the emitting class
// and method. The http and wrapper emitters (internal/api's logging
// middleware, internal/garmin's execute/forwardWrapperStderr) tag their
// own type instead.
func App(class, method string) *slog.Logger {
return slog.Default().With("type", "app", "class", class, "method", method)
// App returns the default logger tagged with the schema fields for an
// ordinary application record (type=app), deriving the emitting location
// from the caller via the runtime: package, file, class (the receiver
// type, omitted for free functions), method. Derivation instead of
// hand-typed strings means the labels can never drift from the code. The
// http and wrapper emitters (internal/api's logging middleware,
// internal/garmin's execute/forwardWrapperStderr) tag their own type and
// location instead.
func App() *slog.Logger {
pkg, file, class, method := location(1)
logger := slog.Default().With("type", "app", "package", pkg, "file", file)
if class != "" {
logger = logger.With("class", class)
}
return logger.With("method", method)
}
// location resolves the caller (skip frames above this function's caller)
// into the log schema's package/file/class/method fields. A method's
// runtime name looks like "geniusrun/backend/internal/api.(*Server).X";
// a free function's like "geniusrun/backend/internal/api.X"; a closure
// gets its parent's name plus ".funcN", kept verbatim in method.
func location(skip int) (pkg, file, class, method string) {
pc, path, _, ok := runtime.Caller(skip + 1)
if !ok {
return "unknown", "unknown", "", "unknown"
}
file = filepath.Base(path)
full := runtime.FuncForPC(pc).Name()
base := full[strings.LastIndex(full, "/")+1:]
pkg, rest, _ := strings.Cut(base, ".")
if strings.HasPrefix(rest, "(*") {
if end := strings.Index(rest, ")."); end != -1 {
class = rest[2:end]
rest = rest[end+2:]
}
}
return pkg, file, class, rest
}
func parseLevel(level string) slog.Level {

View File

@@ -60,13 +60,19 @@ func TestApp_TagsMandatoryFields(t *testing.T) {
slog.SetDefault(NewLogger("info", &buf))
defer slog.SetDefault(prev)
App("api.Server", "handleThing").Info("did it", "extra", 1)
App().Info("did it", "extra", 1)
var decoded map[string]any
if err := json.Unmarshal(buf.Bytes(), &decoded); err != nil {
t.Fatalf("output not JSON: %v", err)
}
if decoded["type"] != "app" || decoded["class"] != "api.Server" || decoded["method"] != "handleThing" {
t.Errorf("mandatory fields = %+v, want type=app class=api.Server method=handleThing", decoded)
if decoded["type"] != "app" || decoded["package"] != "log" || decoded["file"] != "log_test.go" {
t.Errorf("fields = %+v, want type=app package=log (import-path element) file=log_test.go", decoded)
}
if decoded["method"] != "TestApp_TagsMandatoryFields" {
t.Errorf("method = %v, want the emitting function name", decoded["method"])
}
if _, hasClass := decoded["class"]; hasClass {
t.Errorf("class should be omitted for a free function, got %v", decoded["class"])
}
}