Skip to content

Commit 0fc0b94

Browse files
committed
refactor: refactor: introduce package-scoped loggers and improve logging consistency across AI modules
1 parent d0fff1a commit 0fc0b94

18 files changed

Lines changed: 88 additions & 59 deletions

File tree

pkg/ai/cache/cache.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ import (
1414
"github.com/samber/lo"
1515
)
1616

17+
// log is the package-scoped logger for AI providers. Its level follows
18+
// -v/--log-level and can be tuned with -Plog.level.ai=debug.
19+
var log = logger.GetLogger("ai")
20+
1721
var (
1822
ErrCacheDisabled = errors.New("caching is disabled")
1923
ErrNotFound = errors.New("cache entry not found")
@@ -178,7 +182,7 @@ func (c *Cache) Set(entry *Entry) error {
178182
entry.CacheKey = generateCacheKey(entry.Prompt, entry.Model)
179183
entry.PromptHash = entry.CacheKey
180184

181-
logger.Tracef("[%s] caching response for %s (hash:%s)", entry.Model, lo.Ellipsis(entry.Prompt, 20), entry.PromptHash)
185+
log.Tracef("[%s] caching response for %s (hash:%s)", entry.Model, lo.Ellipsis(entry.Prompt, 20), entry.PromptHash)
182186

183187
var expiresAt *time.Time
184188
if c.config.TTL > 0 {

pkg/ai/history/codex_parser.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@ import (
88
"path/filepath"
99
"strings"
1010
"time"
11-
12-
"github.com/flanksource/commons/logger"
1311
)
1412

1513
func ParseCodexLine(line string) (CodexEvent, error) {
@@ -134,7 +132,7 @@ func ExtractCodexToolUsesFromReader(r io.Reader) ([]ToolUse, error) {
134132

135133
event, err := ParseCodexLine(line)
136134
if err != nil {
137-
logger.Debugf("Error parsing codex line: %v", err)
135+
log.Debugf("Error parsing codex line: %v", err)
138136
continue
139137
}
140138

pkg/ai/history/modified_files.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import (
44
"fmt"
55
"os"
66
"path/filepath"
7-
8-
"github.com/flanksource/commons/logger"
97
)
108

119
// fileMutatingTools are the Claude Code tools whose tool_use input names a file
@@ -86,7 +84,7 @@ func FindSessionFile(sessionID string) (string, error) {
8684
newest, newestMod = m, mod
8785
}
8886
}
89-
logger.Warnf("session %s matched %d logs; using most recent %s", sessionID, len(matches), newest)
87+
log.Warnf("session %s matched %d logs; using most recent %s", sessionID, len(matches), newest)
9088
return newest, nil
9189
}
9290
}

pkg/ai/history/parser.go

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,18 @@ import (
1414
"github.com/flanksource/commons/logger"
1515
)
1616

17+
// log is the package-scoped logger for session-history parsing. Its level
18+
// follows -v/--log-level and can be tuned with -Plog.level.history=debug.
19+
var log = logger.GetLogger("history")
20+
1721
func NormalizePath(path string) string {
1822
normalized := strings.ReplaceAll(path, "/", "-")
1923
return strings.ReplaceAll(normalized, ".", "-")
2024
}
2125

2226
func FindSessionFiles(projectsDir, currentDir string, searchAll bool) ([]string, error) {
2327
if _, err := os.Stat(projectsDir); os.IsNotExist(err) {
24-
logger.Debugf("Projects directory does not exist: %s", projectsDir)
28+
log.Debugf("Projects directory does not exist: %s", projectsDir)
2529
return nil, nil
2630
}
2731

@@ -30,12 +34,12 @@ func FindSessionFiles(projectsDir, currentDir string, searchAll bool) ([]string,
3034
return nil, err
3135
}
3236

33-
logger.Debugf("Found %d project directories in %s", len(entries), projectsDir)
37+
log.Debugf("Found %d project directories in %s", len(entries), projectsDir)
3438

3539
var normalized string
3640
if !searchAll && currentDir != "" {
3741
normalized = NormalizePath(currentDir)
38-
logger.Debugf("Looking for directories matching: %s", normalized)
42+
log.Debugf("Looking for directories matching: %s", normalized)
3943
}
4044

4145
var sessionFiles []string
@@ -50,20 +54,20 @@ func FindSessionFiles(projectsDir, currentDir string, searchAll bool) ([]string,
5054
if !hasSuffixFold(entry.Name(), normalized) {
5155
continue
5256
}
53-
logger.Debugf("Matched directory: %s", entry.Name())
57+
log.Debugf("Matched directory: %s", entry.Name())
5458
}
5559

5660
matches, err := filepath.Glob(filepath.Join(projectPath, "*.jsonl"))
5761
if err != nil {
58-
logger.Warnf("Error globbing session files in %s: %v", projectPath, err)
62+
log.Warnf("Error globbing session files in %s: %v", projectPath, err)
5963
continue
6064
}
6165

62-
logger.Debugf("Found %d session files in %s", len(matches), projectPath)
66+
log.Debugf("Found %d session files in %s", len(matches), projectPath)
6367
sessionFiles = append(sessionFiles, matches...)
6468
}
6569

66-
logger.Debugf("Total session files found: %d", len(sessionFiles))
70+
log.Debugf("Total session files found: %d", len(sessionFiles))
6771
return sessionFiles, nil
6872
}
6973

@@ -93,7 +97,7 @@ func ExtractToolUses(sessionFile string) ([]ToolUse, error) {
9397

9498
var entry SessionEntry
9599
if err := json.Unmarshal([]byte(line), &entry); err != nil {
96-
logger.Debugf("Error parsing line in %s: %v", sessionFile, err)
100+
log.Debugf("Error parsing line in %s: %v", sessionFile, err)
97101
continue
98102
}
99103

@@ -232,7 +236,7 @@ func ParseHistory(currentDir string, searchAll bool, filter Filter) (*ParseResul
232236
for _, f := range claudeFiles {
233237
toolUses, err := ExtractToolUses(f)
234238
if err != nil {
235-
logger.Warnf("Error extracting tool uses from %s: %v", f, err)
239+
log.Warnf("Error extracting tool uses from %s: %v", f, err)
236240
continue
237241
}
238242
if len(toolUses) > 0 {
@@ -245,13 +249,13 @@ func ParseHistory(currentDir string, searchAll bool, filter Filter) (*ParseResul
245249
if filter.Source == "" || filter.Source == "codex" {
246250
codexFiles, err := FindCodexSessionFiles()
247251
if err != nil {
248-
logger.Warnf("Error finding codex sessions: %v", err)
252+
log.Warnf("Error finding codex sessions: %v", err)
249253
} else {
250254
result.SessionsFound += len(codexFiles)
251255
for _, f := range codexFiles {
252256
toolUses, err := ExtractCodexToolUses(f)
253257
if err != nil {
254-
logger.Warnf("Error extracting codex tool uses from %s: %v", f, err)
258+
log.Warnf("Error extracting codex tool uses from %s: %v", f, err)
255259
continue
256260
}
257261
if len(toolUses) > 0 {

pkg/ai/history/pretty.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"github.com/flanksource/clicky"
1111
"github.com/flanksource/clicky/api"
1212
"github.com/flanksource/clicky/api/icons"
13-
"github.com/flanksource/commons/logger"
1413
)
1514

1615
// Preview line limits matching pi-mono's tool-execution.ts
@@ -46,7 +45,7 @@ func (t ToolUse) Pretty() api.Text {
4645
text = text.Append(t.Timestamp.Format("2006-01-02")+" ", "text-gray-500")
4746
}
4847
}
49-
if logger.IsDebugEnabled() && t.CWD != "" {
48+
if log.IsDebugEnabled() && t.CWD != "" {
5049
text = text.Add(icons.Folder).Append(" "+getRelativePath(t.CWD, cwd), "text-gray-400 text-xs")
5150
}
5251

pkg/ai/middleware/caching.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77

88
"github.com/flanksource/captain/pkg/ai"
99
"github.com/flanksource/captain/pkg/ai/cache"
10-
"github.com/flanksource/commons/logger"
1110
)
1211

1312
type cachingProvider struct {
@@ -25,7 +24,7 @@ func (c *cachingProvider) Execute(ctx context.Context, req ai.Request) (*ai.Resp
2524

2625
entry, err := c.cache.Get(req.Prompt, c.provider.GetModel())
2726
if err == nil && entry != nil && entry.Error == "" {
28-
logger.Debugf("[%s/%s] cache hit", c.provider.GetBackend(), c.provider.GetModel())
27+
log.Debugf("[%s/%s] cache hit", c.provider.GetBackend(), c.provider.GetModel())
2928
return &ai.Response{
3029
Text: entry.Response,
3130
Model: entry.Model,
@@ -43,7 +42,7 @@ func (c *cachingProvider) Execute(ctx context.Context, req ai.Request) (*ai.Resp
4342
return nil, err
4443
}
4544

46-
logger.Debugf("[%s/%s] cache miss", c.provider.GetBackend(), c.provider.GetModel())
45+
log.Debugf("[%s/%s] cache miss", c.provider.GetBackend(), c.provider.GetModel())
4746

4847
start := time.Now()
4948
resp, execErr := c.provider.Execute(ctx, req)

pkg/ai/middleware/cost.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"github.com/flanksource/captain/pkg/ai"
88
"github.com/flanksource/captain/pkg/ai/pricing"
99
"github.com/flanksource/captain/pkg/ai/session"
10-
"github.com/flanksource/commons/logger"
1110
)
1211

1312
type costProvider struct {
@@ -40,7 +39,7 @@ func (c *costProvider) Execute(ctx context.Context, req ai.Request) (*ai.Respons
4039
resp.Usage.ReasoningTokens, resp.Usage.CacheReadTokens, resp.Usage.CacheWriteTokens)
4140

4241
if calcErr != nil {
43-
logger.Debugf("Cost calculation failed for %s: %v", resp.Model, calcErr)
42+
log.Debugf("Cost calculation failed for %s: %v", resp.Model, calcErr)
4443
} else {
4544
c.session.AddCost(ai.Cost{
4645
Model: resp.Model,

pkg/ai/middleware/retry.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"time"
88

99
"github.com/flanksource/captain/pkg/ai"
10-
"github.com/flanksource/commons/logger"
1110
)
1211

1312
type RetryConfig struct {
@@ -57,7 +56,7 @@ func (r *retryProvider) Execute(ctx context.Context, req ai.Request) (*ai.Respon
5756
jitter := time.Duration(rand.Int64N(int64(delay) / 4))
5857
delay += jitter
5958

60-
logger.Infof("[%s] retrying after %v (attempt %d/%d): %v",
59+
log.Infof("[%s] retrying after %v (attempt %d/%d): %v",
6160
r.provider.GetModel(), delay, attempt+1, r.config.MaxRetries, err)
6261

6362
select {

pkg/ai/pricing/openrouter.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ import (
1212
"github.com/flanksource/commons/logger"
1313
)
1414

15+
// log is the package-scoped logger for AI providers. Its level follows
16+
// -v/--log-level and can be tuned with -Plog.level.ai=debug.
17+
var log = logger.GetLogger("ai")
18+
1519
const (
1620
openRouterAPIURL = "https://openrouter.ai/api/v1/models"
1721
cacheExpiryDuration = 24 * time.Hour
@@ -68,7 +72,7 @@ func EnsureLoaded() {
6872

6973
if pricingCache == nil {
7074
if cache, err := loadFromDisk(); err == nil && cache != nil && !cache.IsExpired() {
71-
logger.Debugf("Loaded OpenRouter pricing from cache (age: %s)", time.Since(cache.Timestamp))
75+
log.Debugf("Loaded OpenRouter pricing from cache (age: %s)", time.Since(cache.Timestamp))
7276
pricingCache = cache
7377
MergeModels(cache.Models)
7478
return
@@ -77,7 +81,7 @@ func EnsureLoaded() {
7781

7882
models, err := fetchOpenRouterPricing()
7983
if err != nil {
80-
logger.Warnf("Failed to fetch OpenRouter pricing: %v", err)
84+
log.Warnf("Failed to fetch OpenRouter pricing: %v", err)
8185
pricingCacheErr = err
8286
return
8387
}
@@ -106,7 +110,7 @@ func fetchOpenRouterPricing() (map[string]*ModelInfo, error) {
106110

107111
cache := &PricingCache{Timestamp: time.Now(), Models: models}
108112
if err := saveToDisk(cache); err != nil {
109-
logger.Warnf("Failed to save OpenRouter pricing cache: %v", err)
113+
log.Warnf("Failed to save OpenRouter pricing cache: %v", err)
110114
}
111115

112116
return models, nil

pkg/ai/provider/codex_appserver.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ import (
1414
"github.com/flanksource/commons/logger"
1515
)
1616

17+
// log is the package-scoped logger for AI providers. Its level follows
18+
// -v/--log-level and can be tuned with -Plog.level.ai=debug.
19+
var log = logger.GetLogger("ai")
20+
1721
// CodexAppServer drives `codex app-server` over JSON-RPC 2.0 stdio (the codex
1822
// app-server v2 schema: slash-delimited methods, camelCase params), replacing
1923
// the one-shot `codex exec --json` path in codex_cli.go. Each Execute runs one
@@ -167,7 +171,7 @@ func (c *CodexAppServer) ensureStarted(ctx context.Context) error {
167171
c.mu.Lock()
168172
c.sup = sup
169173
c.mu.Unlock()
170-
logger.Debugf("[codex-appserver] starting codex app-server")
174+
log.Debugf("[codex-appserver] starting codex app-server")
171175
sup.Start()
172176

173177
select {

0 commit comments

Comments
 (0)