-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.go
More file actions
308 lines (265 loc) · 8.68 KB
/
logger.go
File metadata and controls
308 lines (265 loc) · 8.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package main
import (
"context"
"fmt"
"io"
"log"
"os"
)
// LogLevel represents logging verbosity.
type LogLevel int
const (
LogLevelError LogLevel = iota // Always shown
LogLevelWarn // Always shown
LogLevelInfo // Normal mode
LogLevelDebug // Verbose mode only
)
// Logger provides structured, leveled logging with color support.
type Logger struct {
level LogLevel
useColors bool
errorLog *log.Logger
warnLog *log.Logger
infoLog *log.Logger
debugLog *log.Logger
}
// NewLogger creates a logger with specified level.
func NewLogger(verbose bool) *Logger {
level := LogLevelInfo
if verbose {
level = LogLevelDebug
}
return &Logger{
level: level,
useColors: isTerminal(),
errorLog: log.New(os.Stderr, "", 0),
warnLog: log.New(os.Stdout, "", 0),
infoLog: log.New(os.Stdout, "", 0),
debugLog: log.New(os.Stdout, "", 0),
}
}
// SetOutput sets the output for all loggers.
func (l *Logger) SetOutput(w io.Writer) {
l.errorLog.SetOutput(w)
l.warnLog.SetOutput(w)
l.infoLog.SetOutput(w)
l.debugLog.SetOutput(w)
}
// colorize applies color formatting if colors are enabled.
func (l *Logger) colorize(color, text string) string {
if !l.useColors {
return text
}
return color + text + colorReset
}
// Info logs informational messages (always visible in normal mode).
func (l *Logger) Info(format string, args ...any) {
if l.level >= LogLevelInfo {
msg := fmt.Sprintf(format, args...)
l.infoLog.Println(msg)
}
}
// InfoSuccess logs success with green checkmark.
func (l *Logger) InfoSuccess(format string, args ...any) {
if l.level >= LogLevelInfo {
icon := l.colorize(colorGreen, "✓")
msg := fmt.Sprintf(format, args...)
l.infoLog.Printf("%s %s", icon, msg)
}
}
// InfoDryRun logs dry run "updates" with cyan arrow.
func (l *Logger) InfoDryRun(format string, args ...any) {
if l.level >= LogLevelInfo {
icon := l.colorize(colorCyan, "→")
msg := fmt.Sprintf(format, args...)
l.infoLog.Printf("%s %s", icon, msg)
}
}
// InfoUpdate logs an update operation.
func (l *Logger) InfoUpdate(title, detail string) {
if l.level >= LogLevelInfo {
icon := l.colorize(colorGreen, "✓")
titleColored := l.colorize(colorCyan, title)
l.infoLog.Printf("%s Updated: %s %s", icon, titleColored, detail)
}
}
// Warn logs warnings (always visible).
func (l *Logger) Warn(format string, args ...any) {
if l.level >= LogLevelWarn {
icon := l.colorize(colorYellow, "⚠")
msg := fmt.Sprintf(format, args...)
l.warnLog.Printf("%s %s", icon, msg)
}
}
// Error logs errors (always visible).
func (l *Logger) Error(format string, args ...any) {
if l.level >= LogLevelError {
icon := l.colorize(colorRed, "✗")
msg := fmt.Sprintf(format, args...)
l.errorLog.Printf("%s %s", icon, msg)
}
}
// Debug logs debug information (verbose mode only).
func (l *Logger) Debug(format string, args ...any) {
if l.level >= LogLevelDebug {
msg := fmt.Sprintf(format, args...)
l.debugLog.Printf("[DEBUG] %s", msg)
}
}
// DebugDecision logs decision logic in branches (verbose mode only).
func (l *Logger) DebugDecision(format string, args ...any) {
if l.level >= LogLevelDebug {
msg := fmt.Sprintf(format, args...)
l.debugLog.Printf("[DECISION] %s", msg)
}
}
// DebugHTTP logs HTTP requests and responses (verbose mode only).
func (l *Logger) DebugHTTP(format string, args ...any) {
if l.level >= LogLevelDebug {
msg := fmt.Sprintf(format, args...)
l.debugLog.Printf("[HTTP] %s", msg)
}
}
// Stage logs a high-level stage (e.g., "Authenticating...").
func (l *Logger) Stage(format string, args ...any) {
if l.level >= LogLevelInfo {
msg := fmt.Sprintf(format, args...)
colored := l.colorize(colorBold+colorCyan, msg)
l.infoLog.Println(colored)
}
}
// Progress logs sync progress (overwrites previous line in TTY, single line otherwise).
func (l *Logger) Progress(current, total int, status, title string) {
if l.level < LogLevelInfo {
return
}
if !l.useColors {
// Non-terminal (file/pipe): print each item on its own line
l.infoLog.Printf("[%d/%d] %s: %s", current, total, status, title)
return
}
// Truncate long titles to keep output readable
const maxTitleLen = 150
displayTitle := title
if len(displayTitle) > maxTitleLen {
displayTitle = displayTitle[:maxTitleLen-3] + "..."
}
// Terminal: overwrite line with carriage return
msg := fmt.Sprintf("[%d/%d] %s: %s", current, total, status, displayTitle)
l.infoLog.Print("\r\033[K" + msg) // \033[K clears to end of line
if current == total {
l.infoLog.Println()
}
}
// isTerminal checks if output is a terminal (for color support).
func isTerminal() bool {
// Simple check - if stdout is a terminal
fileInfo, _ := os.Stdout.Stat()
return (fileInfo.Mode() & os.ModeCharDevice) != 0
}
// contextKey is a custom type for context keys to avoid collisions.
type contextKey string
const loggerKey contextKey = "logger"
// WithContext returns a new context with the logger embedded.
func (l *Logger) WithContext(ctx context.Context) context.Context {
return context.WithValue(ctx, loggerKey, l)
}
// LoggerFromContext retrieves the logger from the context
// Returns nil if no logger is set in the context.
func LoggerFromContext(ctx context.Context) *Logger {
if logger, ok := ctx.Value(loggerKey).(*Logger); ok {
return logger
}
return nil
}
// LogInfo logs an informational message using the logger from context.
func LogInfo(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.Info(format, args...)
}
}
// LogInfoSuccess logs a success message using the logger from context.
func LogInfoSuccess(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.InfoSuccess(format, args...)
}
}
// LogInfoUpdate logs an update operation using the logger from context.
func LogInfoUpdate(ctx context.Context, title, detail string) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.InfoUpdate(title, detail)
}
}
// LogInfoDryRun logs a dry run message using the logger from context.
func LogInfoDryRun(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.InfoDryRun(format, args...)
}
}
// LogWarn logs a warning using the logger from context.
func LogWarn(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.Warn(format, args...)
}
}
// LogError logs an error using the logger from context.
func LogError(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.Error(format, args...)
}
}
// LogDebug logs debug information using the logger from context.
func LogDebug(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.Debug(format, args...)
}
}
// LogDebugDecision logs decision logic using the logger from context.
func LogDebugDecision(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.DebugDecision(format, args...)
}
}
// LogDebugHTTP logs HTTP requests/responses using the logger from context.
func LogDebugHTTP(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.DebugHTTP(format, args...)
}
}
// LogStage logs a high-level stage using the logger from context.
func LogStage(ctx context.Context, format string, args ...any) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.Stage(format, args...)
}
}
// LogProgress logs sync progress using the logger from context.
func LogProgress(ctx context.Context, current, total int, status, title string) {
if logger := LoggerFromContext(ctx); logger != nil {
logger.Progress(current, total, status, title)
}
}
// SyncDirection represents the sync direction.
type SyncDirection bool
const (
SyncDirectionForward SyncDirection = false // AniList → MAL
SyncDirectionReverse SyncDirection = true // MAL → AniList
)
// DirectionFromContext extracts sync direction from context
// Returns SyncDirectionForward (default) if no value is set.
func DirectionFromContext(ctx context.Context) SyncDirection {
if dir, ok := ctx.Value(contextKey("direction")).(SyncDirection); ok {
return dir
}
return SyncDirectionForward
}
// WithDirection returns a new context with sync direction embedded.
func WithDirection(ctx context.Context, dir SyncDirection) context.Context {
return context.WithValue(ctx, contextKey("direction"), dir)
}
// String returns the string representation of SyncDirection for JSON serialization.
func (d SyncDirection) String() string {
if d == SyncDirectionReverse {
return DirectionReverseStr
}
return DirectionForwardStr
}