-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebugging.go
More file actions
292 lines (246 loc) · 6.59 KB
/
debugging.go
File metadata and controls
292 lines (246 loc) · 6.59 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
package twig
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
)
// DebugLevel represents the verbosity level of debugging
type DebugLevel int
const (
// Debug levels
DebugOff DebugLevel = iota
DebugError
DebugWarning
DebugInfo
DebugVerbose
)
// Debugger provides logging and debugging tools for the Twig engine
type Debugger struct {
mu sync.Mutex
level DebugLevel
writer io.Writer
logger *log.Logger
traces []string
enabled bool
filename string
line int
}
// Global debugger instance
var debugger = &Debugger{
level: DebugOff,
writer: os.Stderr,
logger: log.New(os.Stderr, "[TWIG] ", log.LstdFlags),
enabled: false,
}
// SetDebugLevel sets the global debug level
func SetDebugLevel(level DebugLevel) {
debugger.mu.Lock()
defer debugger.mu.Unlock()
debugger.level = level
debugger.enabled = level > DebugOff
}
// SetDebugWriter sets the output writer for debug messages
func SetDebugWriter(w io.Writer) {
debugger.mu.Lock()
defer debugger.mu.Unlock()
debugger.writer = w
debugger.logger = log.New(w, "[TWIG] ", log.LstdFlags)
}
// IsDebugEnabled returns true if debugging is enabled
func IsDebugEnabled() bool {
return debugger.enabled
}
// LogError logs an error with source information
func LogError(err error, context ...string) {
if debugger.level >= DebugError {
_, file, line, _ := runtime.Caller(1)
contextStr := ""
if len(context) > 0 {
contextStr = " " + strings.Join(context, " ")
}
debugger.logger.Printf("ERROR:%s:%d:%s%s", filepath.Base(file), line, err, contextStr)
}
}
// LogWarning logs a warning with source information
func LogWarning(msg string, args ...interface{}) {
if debugger.level >= DebugWarning {
_, file, line, _ := runtime.Caller(1)
debugger.logger.Printf("WARNING:%s:%d:%s", filepath.Base(file), line, fmt.Sprintf(msg, args...))
}
}
// LogInfo logs an informational message
func LogInfo(msg string, args ...interface{}) {
if debugger.level >= DebugInfo {
debugger.logger.Printf("INFO:%s", fmt.Sprintf(msg, args...))
}
}
// LogVerbose logs detailed information for debugging
func LogVerbose(msg string, args ...interface{}) {
if debugger.level >= DebugVerbose {
_, file, line, _ := runtime.Caller(1)
debugger.logger.Printf("VERBOSE:%s:%d:%s", filepath.Base(file), line, fmt.Sprintf(msg, args...))
}
}
// LogDebug logs debugging information when debug mode is enabled
func LogDebug(msg string, args ...interface{}) {
if debugger.enabled {
debugger.logger.Printf("DEBUG:%s", fmt.Sprintf(msg, args...))
}
}
// StartTrace begins a trace of template rendering
func StartTrace(templateName string) func() {
if !debugger.enabled {
return func() {}
}
traceID := fmt.Sprintf("TRACE-%s-%d", templateName, time.Now().UnixNano())
start := time.Now()
debugger.mu.Lock()
debugger.traces = append(debugger.traces, traceID)
debugger.mu.Unlock()
LogInfo("Begin rendering template: %s", templateName)
return func() {
elapsed := time.Since(start)
LogInfo("Completed rendering template: %s (took %s)", templateName, elapsed)
debugger.mu.Lock()
defer debugger.mu.Unlock()
// Remove this trace from active traces
for i, t := range debugger.traces {
if t == traceID {
debugger.traces = append(debugger.traces[:i], debugger.traces[i+1:]...)
break
}
}
}
}
// TraceSection traces a section of template rendering
func TraceSection(name string) func() {
if !debugger.enabled {
return func() {}
}
start := time.Now()
LogVerbose("Begin section: %s", name)
return func() {
elapsed := time.Since(start)
LogVerbose("End section: %s (took %s)", name, elapsed)
}
}
// DebugRender enables detailed rendering information
func DebugRender(w io.Writer, tmpl *Template, ctx *RenderContext) error {
if !debugger.enabled {
return tmpl.RenderTo(w, ctx.context)
}
LogInfo("Rendering template %s with context containing %d variables",
tmpl.name, len(ctx.context))
// Log context variables at verbose level
if debugger.level >= DebugVerbose {
for k, v := range ctx.context {
typeName := "nil"
if v != nil {
typeName = fmt.Sprintf("%T", v)
}
LogVerbose("Context var: %s = %v (type: %s)", k, v, typeName)
}
}
// Trace full template rendering
defer StartTrace(tmpl.name)()
return tmpl.RenderTo(w, ctx.context)
}
// FormatErrorContext creates a formatted context for syntax errors
// including the source line and position indicator
func FormatErrorContext(source string, position int, line int) string {
if source == "" || position < 0 {
return ""
}
lines := strings.Split(source, "\n")
if line <= 0 || line > len(lines) {
return ""
}
// Get the problematic line
errorLine := lines[line-1]
// Calculate column position within the line
lineStartIdx := 0
for i := 0; i < line-1; i++ {
lineStartIdx += len(lines[i]) + 1 // +1 for the newline
}
colPosition := position - lineStartIdx
// Ensure column position is valid
if colPosition < 0 {
colPosition = 0
}
if colPosition > len(errorLine) {
colPosition = len(errorLine)
}
// Build the context output
context := fmt.Sprintf("Line %d: %s\n", line, errorLine)
if colPosition >= 0 {
context += strings.Repeat(" ", colPosition+8) + "^\n"
}
return context
}
// EnhancedError provides more detailed error information for debugging
type EnhancedError struct {
Err error
Template string
Line int
Column int
Source string
SourceCtx string
}
// Error implements the error interface
func (e *EnhancedError) Error() string {
if e.Err == nil {
return "unknown error"
}
location := ""
if e.Template != "" {
location = fmt.Sprintf("in template '%s' ", e.Template)
}
position := ""
if e.Line > 0 {
position = fmt.Sprintf("at line %d", e.Line)
if e.Column > 0 {
position += fmt.Sprintf(", column %d", e.Column)
}
}
context := ""
if e.SourceCtx != "" {
context = "\n" + e.SourceCtx
}
return fmt.Sprintf("Error %s%s: %s%s", location, position, e.Err.Error(), context)
}
// Unwrap returns the underlying error
func (e *EnhancedError) Unwrap() error {
return e.Err
}
// NewError creates an enhanced error with context
func NewError(err error, tmpl string, line int, col int, source string) error {
if err == nil {
return nil
}
e := &EnhancedError{
Err: err,
Template: tmpl,
Line: line,
Column: col,
Source: source,
}
if source != "" && line > 0 {
position := 0
if col > 0 {
// Calculate position from line and column
lines := strings.Split(source, "\n")
for i := 0; i < line-1 && i < len(lines); i++ {
position += len(lines[i]) + 1 // +1 for newline
}
position += col - 1
}
e.SourceCtx = FormatErrorContext(source, position, line)
}
return e
}