From 19570ad4bb6dd40320598f8eb30ac75ffe5a8e00 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 26 Oct 2026 00:18:39 +1100 Subject: [PATCH] fix(logging): route ui, messaging and playbook logs through the service log --- internal/app/archiemessaging/config.go | 8 +++---- internal/app/archiemessaging/run.go | 21 ++++++++++--------- internal/app/archieplaybooks/lint.go | 3 ++- internal/app/archieui/config.go | 11 +++++++--- internal/app/archieui/options.go | 4 ++-- internal/app/archieui/run.go | 18 +++++++--------- internal/app/servicekit/config.go | 6 ------ internal/app/statestore/toolcalls.go | 2 +- internal/channels/ephemeral.go | 2 +- internal/daemon/daemon.go | 18 ++++++++++++---- internal/domain/eda/module/module.go | 18 ++++++++-------- internal/forge/noop.go | 2 +- .../controlplanestore/playbooks.go | 11 +++++----- .../controlplanestore/playbooks_client.go | 2 +- internal/webui/live_hub.go | 3 --- internal/worktree/worktree.go | 2 +- 16 files changed, 69 insertions(+), 62 deletions(-) diff --git a/internal/app/archiemessaging/config.go b/internal/app/archiemessaging/config.go index f29df79c7..a77901143 100644 --- a/internal/app/archiemessaging/config.go +++ b/internal/app/archiemessaging/config.go @@ -26,7 +26,7 @@ type ResolvedConfig struct { WorkDir string BotUser string ShowToolCalls bool - Telemetry config.Telemetry + Logging config.Config } type projection struct { @@ -38,7 +38,7 @@ type projection struct { workDir string botUser string showToolCalls bool - telemetry config.Telemetry + logging config.Config } // Resolve loads the configuration, extracts the messaging projection and @@ -73,7 +73,7 @@ func Resolve(o Options, log *slog.Logger) (ResolvedConfig, error) { WorkDir: proj.workDir, BotUser: proj.botUser, ShowToolCalls: proj.showToolCalls, - Telemetry: proj.telemetry, + Logging: proj.logging, }, nil } @@ -98,7 +98,7 @@ func project(cfg config.Config) projection { workDir: cfg.WorkDir, botUser: cfg.BotUser, showToolCalls: cfg.Chat.ShowToolCalls, - telemetry: cfg.Telemetry, + logging: config.Config{StateDir: cfg.StateDir, Log: cfg.Log, Telemetry: cfg.Telemetry}, } } diff --git a/internal/app/archiemessaging/run.go b/internal/app/archiemessaging/run.go index ce6c5bb85..139611723 100644 --- a/internal/app/archiemessaging/run.go +++ b/internal/app/archiemessaging/run.go @@ -5,12 +5,12 @@ import ( "fmt" "log/slog" "net" + "os" "path/filepath" "google.golang.org/grpc" "github.com/samcharles93/archie-core/internal/app/servicekit" - "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/applystatus" "github.com/samcharles93/archie-core/internal/domain/messaging" @@ -23,30 +23,31 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/rpctls" "github.com/samcharles93/archie-core/internal/infrastructure/secretengine" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" - "github.com/samcharles93/archie-core/internal/infrastructure/telemetry" "github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/releaseupdate" "github.com/samcharles93/archie-core/internal/secret" ) // resolveTraced resolves the configuration and starts trace export from it. -func resolveTraced(ctx context.Context, o Options, log *slog.Logger) (ResolvedConfig, func(), error) { - cfg, err := Resolve(o, log) +func resolveLogged(ctx context.Context, o Options) (ResolvedConfig, *slog.Logger, *logging.Feed, func(), error) { + cfg, err := Resolve(o, slog.New(slog.NewJSONHandler(os.Stderr, nil))) if err != nil { - return ResolvedConfig{}, nil, fmt.Errorf("resolve messaging options: %w", err) + return ResolvedConfig{}, nil, nil, nil, fmt.Errorf("resolve messaging options: %w", err) } - stop, err := telemetry.Start(ctx, cfg.Telemetry, "messaging", buildinfo.Version) - return cfg, stop, err + logs, err := servicekit.Logging(ctx, cfg.Logging, "messaging") + if err != nil { + return ResolvedConfig{}, nil, nil, nil, err + } + return cfg, logs.Log.With("service", "archie-messaging"), logs.Feed, func() { _ = logs.Closer.Close() }, nil } // Run runs the standalone Messaging Service process until ctx is cancelled. func Run(ctx context.Context, o Options) error { - log, feed := servicekit.Diagnostics(slog.Default().With("service", "archie-messaging"), presence.Messaging) - cfg, stopTracing, err := resolveTraced(ctx, o, log) + cfg, log, feed, closeLogs, err := resolveLogged(ctx, o) if err != nil { return err } - defer stopTracing() + defer closeLogs() chat, closeGateway, err := gatewayrpc.Dial(cfg.Options.Gateway.Target, cfg.Identity) if err != nil { diff --git a/internal/app/archieplaybooks/lint.go b/internal/app/archieplaybooks/lint.go index d8e2af45c..0e7f7052c 100644 --- a/internal/app/archieplaybooks/lint.go +++ b/internal/app/archieplaybooks/lint.go @@ -5,6 +5,7 @@ package archieplaybooks import ( "fmt" "io" + "log/slog" "github.com/samcharles93/archie-core/internal/domain/eda/module" "github.com/samcharles93/archie-core/internal/domain/eda/playbook" @@ -20,7 +21,7 @@ type Result struct { // LintEDA validates a directory of EDA playbook documents with the compiler // the eda-playbooks resource validates against. func LintEDA(dir string, stderr io.Writer) Result { - if _, err := playbook.Load(dir, module.New()); err != nil { + if _, err := playbook.Load(dir, module.New(slog.New(slog.DiscardHandler))); err != nil { fmt.Fprintln(stderr, err) return Result{ExitCode: 1, Findings: []string{err.Error()}} } diff --git a/internal/app/archieui/config.go b/internal/app/archieui/config.go index 1aa9d3d15..705121ecc 100644 --- a/internal/app/archieui/config.go +++ b/internal/app/archieui/config.go @@ -27,7 +27,7 @@ func Resolve(o Options, log *slog.Logger) (Options, error) { o = merge(o, cfg) tls = cfg.tls o.instance = cfg.instance - o.telemetry = cfg.telemetry + o.logging = cfg.logging } } if o.instance == "" { @@ -71,7 +71,7 @@ type projection struct { tls config.TLS capture CaptureOptions instance string - telemetry config.Telemetry + logging config.Config } func project(cfg config.Config) projection { @@ -84,7 +84,7 @@ func project(cfg config.Config) projection { daemon: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameDaemon).Target}, tls: cfg.TLS, instance: cfg.Instance, - telemetry: cfg.Telemetry, + logging: loggingConfig(cfg), capture: CaptureOptions{ Retention: cfg.Capture.Retention.Std(), MaxEvents: cfg.Capture.MaxEvents, @@ -168,3 +168,8 @@ func mergeTarget(o, p ServiceTarget) ServiceTarget { } return o } + +// loggingConfig narrows cfg to what servicekit.Logging reads. +func loggingConfig(cfg config.Config) config.Config { + return config.Config{StateDir: cfg.StateDir, Log: cfg.Log, Telemetry: cfg.Telemetry} +} diff --git a/internal/app/archieui/options.go b/internal/app/archieui/options.go index c3f80535f..b297dd028 100644 --- a/internal/app/archieui/options.go +++ b/internal/app/archieui/options.go @@ -79,8 +79,8 @@ type Options struct { // instance is the deployment name, from the configuration source or // ARCHIE_INSTANCE. instance string - // telemetry is the [telemetry] section, read only by Run. - telemetry config.Telemetry + // logging is the [log] and [telemetry] configuration, read only by Run. + logging config.Config } // CaptureOptions carries the [capture] settings the capture receiver needs. diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go index c0174e420..b86f9f5d4 100644 --- a/internal/app/archieui/run.go +++ b/internal/app/archieui/run.go @@ -14,7 +14,6 @@ import ( "time" "github.com/samcharles93/archie-core/internal/app/servicekit" - "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/presence" infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" @@ -37,13 +36,13 @@ func buildAccessChain(ctx context.Context, store *staterpc.Client, log *slog.Log } // resolveTraced resolves the options and starts trace export from them. -func resolveTraced(ctx context.Context, options Options, log *slog.Logger) (Options, func(), error) { - opts, err := Resolve(options, log) +func resolveLogged(ctx context.Context, options Options) (Options, servicekit.Logs, error) { + opts, err := Resolve(options, slog.New(slog.NewJSONHandler(os.Stderr, nil))) if err != nil { - return Options{}, nil, err + return Options{}, servicekit.Logs{}, err } - stop, err := telemetry.Start(ctx, opts.telemetry, "ui", buildinfo.Version) - return opts, stop, err + logs, err := servicekit.Logging(ctx, opts.logging, "ui") + return opts, logs, err } // Run serves the dashboard until ctx is cancelled. It resolves its own @@ -51,13 +50,12 @@ func resolveTraced(ctx context.Context, options Options, log *slog.Logger) (Opti // HTTP surface over them, and unwinds listener then clients in reverse order // on shutdown. func Run(ctx context.Context, options Options) error { - log := slog.New(slog.NewJSONHandler(os.Stderr, nil)).With("component", "ui") - log, feed := servicekit.Diagnostics(log, presence.UI) - opts, stopTracing, err := resolveTraced(ctx, options, log) + opts, logs, err := resolveLogged(ctx, options) if err != nil { return err } - defer stopTracing() + defer func() { _ = logs.Closer.Close() }() + log, feed := logs.Log.With("service", presence.UI), logs.Feed warnPlainHTTP(log, opts) var cleanups []func() defer func() { diff --git a/internal/app/servicekit/config.go b/internal/app/servicekit/config.go index 6d92dc898..026989675 100644 --- a/internal/app/servicekit/config.go +++ b/internal/app/servicekit/config.go @@ -75,9 +75,3 @@ func Logging(ctx context.Context, cfg config.Config, component string) (Logs, er type closerFunc func() error func (f closerFunc) Close() error { return f() } - -// Diagnostics captures a service's stderr log for its recent-log contract. -func Diagnostics(log *slog.Logger, service string) (*slog.Logger, *logging.Feed) { - feed := logging.NewFeed(1000) - return slog.New(logging.WithTrace(logging.NewFeedHandler(log.Handler(), feed))).With("service", service), feed -} diff --git a/internal/app/statestore/toolcalls.go b/internal/app/statestore/toolcalls.go index 95fac536b..602fca787 100644 --- a/internal/app/statestore/toolcalls.go +++ b/internal/app/statestore/toolcalls.go @@ -35,7 +35,7 @@ type toolCallProjectingTaskStore struct { func newToolCallProjectingTaskStore(inner storecontract.TaskStore, toolCalls toolCallWriter, log *slog.Logger) *toolCallProjectingTaskStore { if log == nil { - log = slog.Default() + log = slog.New(slog.DiscardHandler) } return &toolCallProjectingTaskStore{TaskStore: inner, toolCalls: toolCalls, log: log} } diff --git a/internal/channels/ephemeral.go b/internal/channels/ephemeral.go index 4d2b608af..0d808e0ca 100644 --- a/internal/channels/ephemeral.go +++ b/internal/channels/ephemeral.go @@ -35,7 +35,7 @@ func NewEphemeralSender(log *slog.Logger, after func(time.Duration) <-chan time. after = time.After } if log == nil { - log = slog.Default() + log = slog.New(slog.DiscardHandler) } return &EphemeralSender{ after: after, diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index f217cf1fb..823b189b0 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -1503,8 +1503,13 @@ func (d *Daemon) reconcilePRs(ctx context.Context) { attempt := t.Attempt switch state { case "merged": - _ = d.Store.Transition(ctx, t.ID, workflow.StatusPROpen, workflow.StatusMerged, "") - _ = trees.Cleanup(t.Owner, t.Repo, t.IssueNumber) + if err := d.Store.Transition(ctx, t.ID, workflow.StatusPROpen, workflow.StatusMerged, ""); err != nil { + d.Log.ErrorContext(ctx, "PR merged but task transition failed", "task", t.ID, "pr", t.PRNumber, "err", err) + continue + } + if err := trees.Cleanup(t.Owner, t.Repo, t.IssueNumber); err != nil { + d.Log.WarnContext(ctx, "worktree cleanup failed", "task", t.ID, "err", err) + } // Close the issue explicitly; nothing else does. d.closeResolvedIssue(ctx, fg, &t, fmt.Sprintf( "Closed by #%d, merged by archie.", t.PRNumber, @@ -1516,8 +1521,13 @@ func (d *Daemon) reconcilePRs(ctx context.Context) { Data: map[string]any{"pr": t.PRNumber}, }) case "closed": - _ = d.Store.Transition(ctx, t.ID, workflow.StatusPROpen, workflow.StatusRejected, "PR closed without merge") - _ = trees.Cleanup(t.Owner, t.Repo, t.IssueNumber) + if err := d.Store.Transition(ctx, t.ID, workflow.StatusPROpen, workflow.StatusRejected, "PR closed without merge"); err != nil { + d.Log.ErrorContext(ctx, "PR rejected but task transition failed", "task", t.ID, "pr", t.PRNumber, "err", err) + continue + } + if err := trees.Cleanup(t.Owner, t.Repo, t.IssueNumber); err != nil { + d.Log.WarnContext(ctx, "worktree cleanup failed", "task", t.ID, "err", err) + } d.Log.InfoContext(ctx, "PR rejected", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber) d.emit(ctx, events.Event{ Kind: events.KindPRRejected, TaskID: t.ID, Attempt: attempt, diff --git a/internal/domain/eda/module/module.go b/internal/domain/eda/module/module.go index d6b6c2218..456862c8c 100644 --- a/internal/domain/eda/module/module.go +++ b/internal/domain/eda/module/module.go @@ -17,7 +17,7 @@ import ( ) // invoker decodes raw args, runs the kind, and marshals its typed result. -type invoker func(ctx context.Context, rawArgs map[string]any) (map[string]any, error) +type invoker func(ctx context.Context, log *slog.Logger, rawArgs map[string]any) (map[string]any, error) // Kind is one built-in action kind: its schema and how to run it. type Kind struct { @@ -37,11 +37,11 @@ var registry = map[string]Kind{ } // ModuleRegistry answers the playbook engine's questions about action kinds. -// It holds no state: every kind is built in. -type ModuleRegistry struct{} +// Every kind is built in; log is where the log kind writes. +type ModuleRegistry struct{ log *slog.Logger } -// New returns the registry. -func New() *ModuleRegistry { return &ModuleRegistry{} } +// New returns the registry. The log kind writes to log. +func New(log *slog.Logger) *ModuleRegistry { return &ModuleRegistry{log: log} } // KindSchema returns a known kind's Args and Result types. func (*ModuleRegistry) KindSchema(kind string) (reflect.Type, reflect.Type, bool) { @@ -54,7 +54,7 @@ func (*ModuleRegistry) KindSchema(kind string) (reflect.Type, reflect.Type, bool // runLog writes the message to the daemon's log at the requested level // (default info) and reports what it wrote. -func runLog(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { +func runLog(ctx context.Context, logger *slog.Logger, rawArgs map[string]any) (map[string]any, error) { args, err := decodeLogArgs(rawArgs) if err != nil { return nil, err @@ -64,7 +64,7 @@ func runLog(ctx context.Context, rawArgs map[string]any) (map[string]any, error) return nil, err } if args.Message != "" { - slog.Default().Log(ctx, level, args.Message) + logger.Log(ctx, level, args.Message) } return map[string]any{"written": args.Message != "", "level": name}, nil } @@ -114,12 +114,12 @@ func decodeLogArgs(rawArgs map[string]any) (log.Args, error) { } // Invoke calls kind with rawArgs and returns its result map. -func (*ModuleRegistry) Invoke(ctx context.Context, kind string, rawArgs map[string]any) (map[string]any, error) { +func (r *ModuleRegistry) Invoke(ctx context.Context, kind string, rawArgs map[string]any) (map[string]any, error) { k, ok := registry[kind] if !ok { return nil, fmt.Errorf("module: unknown kind %q", kind) } - res, err := k.invoke(ctx, rawArgs) + res, err := k.invoke(ctx, r.log, rawArgs) if err != nil { return nil, fmt.Errorf("module %s: %w", kind, err) } diff --git a/internal/forge/noop.go b/internal/forge/noop.go index 5c45f9877..befc4719d 100644 --- a/internal/forge/noop.go +++ b/internal/forge/noop.go @@ -13,7 +13,7 @@ type NoopForge struct { // NewNoop returns a NoopForge instance. func NewNoop(log *slog.Logger) Forge { if log == nil { - log = slog.Default() + log = slog.New(slog.DiscardHandler) } return &NoopForge{log: log} } diff --git a/internal/infrastructure/controlplanestore/playbooks.go b/internal/infrastructure/controlplanestore/playbooks.go index 31b119cd8..8cc6b2c9f 100644 --- a/internal/infrastructure/controlplanestore/playbooks.go +++ b/internal/infrastructure/controlplanestore/playbooks.go @@ -3,6 +3,7 @@ package controlplanestore import ( "encoding/json" "fmt" + "log/slog" "path" "github.com/samcharles93/archie-core/internal/config" @@ -35,7 +36,7 @@ func playbooksDefinition() Definition { Seed: func(config.Config) any { return PlaybookCollection{Playbooks: []PlaybookEntry{}} }, Validate: func(input []byte) error { return validateAs(input, func(c PlaybookCollection) error { - _, err := CompilePlaybooks(c) + _, err := CompilePlaybooks(c, slog.New(slog.DiscardHandler)) return err }) }, @@ -43,8 +44,8 @@ func playbooksDefinition() Definition { } // CompilePlaybooks compiles a collection against the module vocabulary. Any -// invalid playbook fails the set. -func CompilePlaybooks(c PlaybookCollection) (*playbook.Store, error) { +// invalid playbook fails the set. Playbook log actions write to log. +func CompilePlaybooks(c PlaybookCollection, log *slog.Logger) (*playbook.Store, error) { docs := make([]playbook.Document, 0, len(c.Playbooks)) seen := map[string]bool{} for _, entry := range c.Playbooks { @@ -54,7 +55,7 @@ func CompilePlaybooks(c PlaybookCollection) (*playbook.Store, error) { seen[entry.ID] = true docs = append(docs, playbook.Document{ID: entry.ID, YAML: []byte(entry.YAML)}) } - store, err := playbook.Compile(docs, module.New()) + store, err := playbook.Compile(docs, module.New(log)) if err != nil { return nil, fmt.Errorf("%w: %w", ErrValidation, err) } @@ -92,7 +93,7 @@ func decodePlaybooks(value []byte) (PlaybookCollection, error) { } func encodePlaybooks(collection PlaybookCollection) ([]byte, error) { - if _, err := CompilePlaybooks(collection); err != nil { + if _, err := CompilePlaybooks(collection, slog.New(slog.DiscardHandler)); err != nil { return nil, err } return json.Marshal(collection) diff --git a/internal/infrastructure/controlplanestore/playbooks_client.go b/internal/infrastructure/controlplanestore/playbooks_client.go index 0d6840311..0c229a46a 100644 --- a/internal/infrastructure/controlplanestore/playbooks_client.go +++ b/internal/infrastructure/controlplanestore/playbooks_client.go @@ -93,7 +93,7 @@ func (l *LivePlaybooks) current(ctx context.Context) *playbook.Store { l.log.ErrorContext(ctx, "eda playbooks undecodable; keeping the last good set", "err", err) return held.store } - store, err := CompilePlaybooks(collection) + store, err := CompilePlaybooks(collection, l.log) if err != nil { l.ApplyStatus.Report(ctx, PlaybooksKind, response.Resource.Version, err) l.log.ErrorContext(ctx, "eda playbooks do not compile; keeping the last good set", "err", err) diff --git a/internal/webui/live_hub.go b/internal/webui/live_hub.go index 23effa36b..45a377867 100644 --- a/internal/webui/live_hub.go +++ b/internal/webui/live_hub.go @@ -3,7 +3,6 @@ package webui import ( "context" "encoding/json" - "log/slog" "maps" "reflect" "slices" @@ -198,8 +197,6 @@ func waitLive(ctx context.Context, delay time.Duration) bool { func (s *Server) logLive(message string, args ...any) { if s.Log != nil { s.Log.Warn(message, args...) - } else { - slog.Default().Warn(message, args...) } } diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index 7fdab5671..2684fe663 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -62,7 +62,7 @@ func (m *Manager) logger() *slog.Logger { if m != nil && m.Log != nil { return m.Log } - return slog.Default() + return slog.New(slog.DiscardHandler) } // OrgWorkDir confines an organisation's worktrees beneath root, including