Merge pull request #536 from nirlep1204/chore/migrate-slog-server

chore: migrate log.Printf to log/slog in server management and control
This commit is contained in:
BaaRai
2026-11-27 00:13:24 +01:00
committed by GitHub
9 changed files with 83 additions and 36 deletions
+2 -2
View File
@@ -9,7 +9,7 @@ import (
"errors"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"net/url"
"os"
@@ -242,7 +242,7 @@ func (s *Server) seedPythonInterpreter() {
}
if p := detectPython(); p != "" {
_ = s.m.pg.SetSetting(settingPythonInterp, p)
log.Printf("[custom-tool] auto-detected python interpreter: %s", p)
slog.Info("[custom-tool] auto-detected python interpreter", "path", p)
}
}
+8 -8
View File
@@ -2,7 +2,7 @@ package server
import (
"context"
"log"
"log/slog"
"sync"
"time"
@@ -43,7 +43,7 @@ func newLLMHealthRegistry(ctx context.Context, pg *db.DB) (*llmpool.Registry, *h
st.OpenUntil = *h.OpenUntil
}
reg.Restore(h.ProfileID, st)
log.Printf("[llmpool] restored circuit-breaker state: profile #%d cooling until %s", h.ProfileID, st.OpenUntil.Format(time.RFC3339))
slog.Info("[llmpool] restored circuit-breaker state", "profile_id", h.ProfileID, "cooling_until", st.OpenUntil.Format(time.RFC3339))
}
}
return reg, syncer
@@ -103,7 +103,7 @@ func (s *Server) FlushLLMHealth() {
select {
case <-s.llmHealthSync.done:
case <-time.After(5 * time.Second):
log.Printf("[llmpool] timed out flushing circuit-breaker state")
slog.Warn("[llmpool] timed out flushing circuit-breaker state")
}
}
@@ -114,7 +114,7 @@ func (h *healthSync) enqueue(id int64, op healthOp) {
if h.stopped {
h.mu.Unlock()
if err := h.apply(id, op); err != nil {
log.Printf("[llmpool] write circuit-breaker profile #%d: %v", id, err)
slog.Error("[llmpool] write circuit-breaker profile failed", "profile_id", id, "err", err)
}
return
}
@@ -198,7 +198,7 @@ func (h *healthSync) apply(id int64, op healthOp) error {
func (h *healthSync) write(batch map[int64]healthOp) (failed bool) {
for id, op := range batch {
if err := h.apply(id, op); err != nil {
log.Printf("[llmpool] write circuit-breaker profile #%d: %v", id, err)
slog.Error("[llmpool] write circuit-breaker profile failed", "profile_id", id, "err", err)
h.restore(id, op)
failed = true
}
@@ -214,7 +214,7 @@ func (h *healthSync) finish() {
h.mu.Unlock()
for id, op := range batch {
if err := h.apply(id, op); err != nil {
log.Printf("[llmpool] write circuit-breaker profile #%d: %v", id, err)
slog.Error("[llmpool] write circuit-breaker profile failed", "profile_id", id, "err", err)
}
}
}
@@ -273,7 +273,7 @@ func (s *Server) poolChain(headID int64, headProv llm.Provider, headCfg agent.Co
}
profs, err := s.m.pg.PoolProfiles()
if err != nil {
log.Printf("[llmpool] failed to read the pool chain: %v", err)
slog.Error("[llmpool] failed to read pool chain", "err", err)
return nil
}
var head *db.LLMProfile
@@ -326,7 +326,7 @@ func (s *Server) poolForActive(activeID int64, prov llm.Provider, cfg agent.Conf
for _, m := range pool.Members() {
names = append(names, m.Name+"/"+m.Model)
}
log.Printf("[llmpool] LLM pooling enabled, chain (%d): %v", len(names), names)
slog.Info("[llmpool] LLM pooling enabled", "count", len(names), "chain", names)
return pool
}
+14 -14
View File
@@ -9,7 +9,7 @@ import (
"errors"
"fmt"
"io"
"log"
"log/slog"
"mime"
"net"
"net/http"
@@ -222,7 +222,7 @@ func (s *Server) abortTaskDelete(taskID string) {
state := task.lifecycleSnapshot()
keepPaused = state.Paused || state.Queued
if getErr != nil {
log.Printf("[task-delete] task %s failed to read persisted state, restoring the barrier from in-memory state: %v", taskID, getErr)
slog.Warn("[task-delete] failed to read persisted state, restoring barrier from in-memory state", "task_id", taskID, "err", getErr)
}
} else if getErr == nil {
// The request targeted a task that does not exist. Do not retain a
@@ -376,7 +376,7 @@ func (s *Server) pgCreateAgent(w http.ResponseWriter, r *http.Request) {
}
// starter prompt so the editor shows something editable from the start.
if err := pg.SeedPromptIfEmpty(a.ID, agent.DefaultAssistantPrompt); err != nil {
log.Printf("[agents] failed to seed starter prompt for %s: %v", a.Key, err)
slog.Error("[agents] failed to seed starter prompt", "agent", a.Key, "err", err)
}
writeJSON(w, 200, agentDTO(a))
}
@@ -424,10 +424,10 @@ func (s *Server) pgDeleteAgent(w http.ResponseWriter, r *http.Request) {
return
}
if err := pg.RemoveAgentFromToolBindings(a.Key); err != nil {
log.Printf("[agents] failed to clean up tool bindings for %s: %v", a.Key, err)
slog.Error("[agents] failed to clean up tool bindings", "agent", a.Key, "err", err)
}
if err := pg.DeleteTriggersForAgent(a.Key); err != nil {
log.Printf("[agents] failed to clean up triggers for %s: %v", a.Key, err)
slog.Error("[agents] failed to clean up triggers", "agent", a.Key, "err", err)
}
writeJSON(w, 200, map[string]any{"deleted": a.Key})
}
@@ -865,7 +865,7 @@ func (s *Server) pgListTools(w http.ResponseWriter, r *http.Request) {
// catalog query, so agent assembly never pays for this aggregate.
counts, countErr := pg.ToolUsageCounts()
if countErr != nil {
log.Printf("[tools] failed to read call stats: %v", countErr)
slog.Warn("[tools] failed to read call stats", "err", countErr)
} else {
for _, tool := range ts {
tool.Calls = counts[tool.Key]
@@ -1086,7 +1086,7 @@ func (s *Server) pgSaveMCP(w http.ResponseWriter, r *http.Request) {
m.ID = id
ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second)
if derr := s.discoverAndCacheMCP(ctx, &m); derr != nil {
log.Printf("[mcp] tool discovery after adding %s failed: %v", m.Name, derr)
slog.Error("[mcp] tool discovery failed after adding mcp", "mcp", m.Name, "err", derr)
}
cancel()
}
@@ -1197,7 +1197,7 @@ func (s *Server) fsListSkills(w http.ResponseWriter, r *http.Request) {
if s.m.pg != nil {
stats, err := s.m.pg.SkillStats()
if err != nil {
log.Printf("[skills] failed to read call stats: %v", err)
slog.Warn("[skills] failed to read call stats", "err", err)
}
for _, st := range stats {
statBySkill[st.Skill] = st
@@ -1242,7 +1242,7 @@ func (s *Server) fsSkillUsage(w http.ResponseWriter, r *http.Request) {
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
calls, err := pg.RecentSkillCalls(name, limit)
if err != nil {
log.Printf("[skills] recent calls for %s: %v", name, err)
slog.Error("[skills] failed to read recent calls", "skill", name, "err", err)
writeErr(w, 500, "failed to load skill usage")
return
}
@@ -1259,7 +1259,7 @@ func (s *Server) fsMissingSkills(w http.ResponseWriter, r *http.Request) {
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
missing, err := pg.MissingSkillStats(limit)
if err != nil {
log.Printf("[skills] missing skills: %v", err)
slog.Error("[skills] failed to read missing stats", "err", err)
writeErr(w, 500, "failed to load missing skills")
return
}
@@ -1454,7 +1454,7 @@ func warnBrokenSkills(dir string) {
if s.Dir == "" || s.Name == filepath.Base(s.Dir) {
continue
}
log.Printf("[skill] %s: frontmatter did not parse (loaded under the directory name; description and mcps are empty) - fix the YAML in %s", s.Name, filepath.Join(s.Dir, "SKILL.md"))
slog.Warn("[skill] frontmatter did not parse (loaded under directory name; fix YAML in SKILL.md)", "skill", s.Name, "path", filepath.Join(s.Dir, "SKILL.md"))
}
}
@@ -2046,7 +2046,7 @@ func (s *Server) pgSkillVisibility(w http.ResponseWriter, r *http.Request) {
}
agents, err := pg.SkillAgents(r.PathValue("name"))
if err != nil {
log.Printf("[skills] visibility for %s: %v", r.PathValue("name"), err)
slog.Error("[skills] failed to read visibility", "skill", r.PathValue("name"), "err", err)
writeErr(w, 500, "failed to load skill visibility")
return
}
@@ -2068,7 +2068,7 @@ func (s *Server) pgToggleSkillVisibility(w http.ResponseWriter, r *http.Request)
return
}
if err := pg.ToggleSkillVisibility(body.AgentID, body.SkillName, body.Visible); err != nil {
log.Printf("[skills] toggle visibility for %s: %v", body.SkillName, err)
slog.Error("[skills] failed to toggle visibility", "skill", body.SkillName, "err", err)
writeErr(w, 500, "failed to update skill visibility")
return
}
@@ -2349,7 +2349,7 @@ func (s *Server) restoreTasksAfterProfileDelete(pg *db.DB) {
// paused task remains paused and terminal tasks remain immutable.
if !isTerminalStatus(task.lifecycleSnapshot().Status) && s.taskRuntimeAvailable(task, "planner", "worker") {
if _, reopenErr := task.Store.ReopenIntentsByBlockedReason(db.IntentBlockedLLMQuota); reopenErr != nil {
log.Printf("[llm-profile] task %s reopen quota-blocked intents after profile delete: %v", task.ID, reopenErr)
slog.Warn("[llm-profile] reopen quota-blocked intents failed after profile delete", "task_id", task.ID, "err", reopenErr)
}
}
task.Notify()
+47
View File
@@ -0,0 +1,47 @@
package server
import (
"context"
"log/slog"
"strings"
"sync"
"testing"
)
type triageSlogCapture struct {
mu sync.Mutex
recs []slog.Record
}
func (h *triageSlogCapture) Enabled(context.Context, slog.Level) bool { return true }
func (h *triageSlogCapture) Handle(_ context.Context, r slog.Record) error {
h.mu.Lock()
h.recs = append(h.recs, r.Clone())
h.mu.Unlock()
return nil
}
func (h *triageSlogCapture) WithAttrs([]slog.Attr) slog.Handler { return h }
func (h *triageSlogCapture) WithGroup(string) slog.Handler { return h }
func TestTriageRefusedBaseURLLogsSlogWarn(t *testing.T) {
cap := &triageSlogCapture{}
prev := slog.Default()
slog.SetDefault(slog.New(cap))
t.Cleanup(func() { slog.SetDefault(prev) })
s := &Server{}
if c := s.triageHTTPClient("http://127.0.0.1:9999"); c != nil {
t.Fatalf("expected nil client for loopback base_url, got %v", c)
}
cap.mu.Lock()
defer cap.mu.Unlock()
var sawWarn bool
for _, r := range cap.recs {
if r.Level == slog.LevelWarn && strings.Contains(r.Message, "[triage]") {
sawWarn = true
}
}
if !sawWarn {
t.Fatalf("expected slog.LevelWarn [triage] record; got %d records", len(cap.recs))
}
}
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"os"
"path/filepath"
"strings"
@@ -157,7 +157,7 @@ func (s *Server) deleteRemoteTaskArchive(job *pgdb.TaskArchive) error {
}
if err := s.recoverRemoteArchiveJournal(journal); err != nil {
// The task is gone; the durable outbox retries the remaining object cleanup.
log.Printf("[task-archive] archive %d deleted; remote cleanup pending: %v", job.ID, err)
slog.Warn("[task-archive] archive deleted, remote cleanup pending", "archive_id", job.ID, "err", err)
}
return nil
}
+2 -2
View File
@@ -4,7 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log"
"log/slog"
"net/http"
"strings"
@@ -145,7 +145,7 @@ func (s *Server) applyTaskControlWithCause(t *Task, action string, pauseCause er
default:
return out, fmt.Errorf("action must be pause|resume")
}
log.Printf("[task] #%s %s", t.ID, map[string]string{"pause": "paused", "resume": "resumed"}[action])
slog.Info("[task] task state changed", "task_id", t.ID, "action", map[string]string{"pause": "paused", "resume": "resumed"}[action])
return out, nil
}
+2 -2
View File
@@ -3,7 +3,7 @@ package server
import (
"database/sql"
"errors"
"log"
"log/slog"
"net/http"
"strconv"
)
@@ -23,7 +23,7 @@ func (s *Server) taskOutcome(w http.ResponseWriter, r *http.Request) {
return
}
if err != nil {
log.Printf("[tasks] outcome query failed for %d: %v", id, err)
slog.Error("[tasks] outcome query failed", "task_id", id, "err", err)
writeErr(w, 500, "outcome query failed")
return
}
+3 -3
View File
@@ -5,7 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"net/url"
"strconv"
@@ -145,7 +145,7 @@ func (m *Manager) reloadTamperHooks() {
}
rows, err := m.pg.ListTrafficTamperHooks()
if err != nil {
log.Printf("[traffic] tampering hooks not reloaded: %v", err)
slog.Warn("[traffic] tampering hooks not reloaded", "err", err)
return
}
defs := make([]traffic.HookDef, 0, len(rows))
@@ -165,7 +165,7 @@ func (m *Manager) reloadTamperHooks() {
loadErrs[id] = msg
}
for id, msg := range loadErrs {
log.Printf("[traffic] tampering hook %d not loaded: %s", id, msg)
slog.Warn("[traffic] tampering hook not loaded", "hook_id", id, "msg", msg)
}
m.hookLoadErrs = loadErrs
m.hookSet.Store(hs)
+3 -3
View File
@@ -3,7 +3,7 @@ package server
import (
"context"
"fmt"
"log"
"log/slog"
"net"
"net/http"
"strconv"
@@ -23,7 +23,6 @@ import (
// no base_url/model returns nil, and report_finding behaves exactly as before.
func (s *Server) triageClient() agent.TriageClient {
id := s.triageProfileID()
log.Printf("[triage] triageClient: profile_id=%d", id)
if id <= 0 {
return nil
}
@@ -38,6 +37,7 @@ func (s *Server) triageClient() agent.TriageClient {
if client == nil {
return nil
}
slog.Info("[triage] initialized triage client", "profile_id", id)
return &agent.SystemOneClient{BaseURL: p.BaseURL, APIKey: p.APIKey, Model: p.Model, HTTP: client}
}
@@ -52,7 +52,7 @@ func (s *Server) triageHTTPClient(baseURL string) *http.Client {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if _, err := g.validateURL(ctx, baseURL, "triage"); err != nil {
log.Printf("[triage] base_url refused (%v); dedup stays off", err)
slog.Warn("[triage] base_url refused, dedup stays off", "err", err)
return nil
}
var tr *http.Transport