-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.lua
More file actions
556 lines (473 loc) · 14.2 KB
/
Copy pathlogger.lua
File metadata and controls
556 lines (473 loc) · 14.2 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
-- Logging system for diffusion.nvim
-- Provides structured logging with levels and file output
local Logger = {}
Logger._instance = nil
Logger.levels = {
DEBUG = 1,
INFO = 2,
WARN = 3,
ERROR = 4
}
-- Parse human-readable size strings (e.g., "10M", "5MB", "1G", "500K")
-- Returns size in bytes, or nil if invalid
local function parse_size(size)
if type(size) == "number" then
return size
end
if type(size) ~= "string" then
return nil
end
local num, unit = size:match("^(%d+%.?%d*)%s*([KMGkmg]?)[Bb]?$")
if not num then
return nil
end
num = tonumber(num)
if not num then
return nil
end
unit = (unit or ""):upper()
local multipliers = {
[""] = 1,
["K"] = 1024,
["M"] = 1024 * 1024,
["G"] = 1024 * 1024 * 1024,
}
return math.floor(num * (multipliers[unit] or 1))
end
-- Ensure the Logger class has all required methods
function Logger:_ensure_methods()
-- Ensure all logging methods exist
self.debug = self.debug or function() end
self.info = self.info or function() end
self.warn = self.warn or function() end
self.error = self.error or function() end
self._log = self._log or function() end
end
function Logger:new()
local instance = {
_config = {
enabled = true,
level = Logger.levels.INFO,
file = nil,
max_file_size = 10 * 1024 * 1024, -- 10MB default
max_backup_count = 3, -- Keep 3 rotated files
},
_log_file = nil,
_buffer = {},
_buffer_size = 100,
_stats = {
messages_logged = 0,
errors_logged = 0,
warnings_logged = 0,
rotations = 0,
}
}
setmetatable(instance, { __index = self })
-- Ensure all methods exist on the instance
instance:_ensure_methods()
return instance
end
function Logger:setup(config)
if Logger._instance then
-- Update existing instance with new config (merge) if provided
if config then
Logger._instance._config = vim.tbl_deep_extend("force", Logger._instance._config, config)
if type(Logger._instance._config.level) == "string" then
Logger._instance._config.level = Logger.levels[Logger._instance._config.level] or Logger.levels.INFO
end
if Logger._instance._config.file then
Logger._instance._log_file = Logger._instance._config.file
end
end
return Logger._instance
end
Logger._instance = self:new()
if config then
Logger._instance._config = vim.tbl_deep_extend("force", Logger._instance._config, config)
end
-- Set numeric level from string
if type(Logger._instance._config.level) == "string" then
Logger._instance._config.level = Logger.levels[Logger._instance._config.level] or Logger.levels.INFO
end
-- Parse max_file_size if it's a string (e.g., "10M", "5MB")
if Logger._instance._config.max_file_size then
local parsed = parse_size(Logger._instance._config.max_file_size)
if parsed then
Logger._instance._config.max_file_size = parsed
end
end
-- Setup log file if specified
if Logger._instance._config.file then
Logger._instance._log_file = Logger._instance._config.file
else
-- Use default log file location
local log_dir = vim.fn.stdpath("cache") .. "/diffusion"
local ok, result = pcall(function()
vim.fn.mkdir(log_dir, "p")
return log_dir .. "/diffusion.log"
end)
if ok then
Logger._instance._log_file = result
else
-- Fallback to nil if we can't create the log directory
Logger._instance._log_file = nil
end
end
-- Check for rotation ONCE at startup (not on every write)
if Logger._instance._log_file then
Logger._instance:_check_rotation_on_startup()
Logger._instance:_write_log_header()
end
return Logger._instance
end
-- Check and rotate log file at startup only (no per-write overhead)
function Logger:_check_rotation_on_startup()
if not self._log_file or not self._config.max_file_size then
return
end
local current_size = self:_get_file_size(self._log_file)
if current_size >= self._config.max_file_size then
self:_rotate_logs()
end
end
function Logger:_write_log_header()
if not self._config.enabled or not self._log_file then
return
end
local header = string.format(
"\n--- diffusion.nvim session started at %s ---\n",
os.date("%Y-%m-%d %H:%M:%S")
)
local file = io.open(self._log_file, "a")
if file then
file:write(header)
file:close()
end
end
-- Get file size in bytes, returns 0 if file doesn't exist or error
function Logger:_get_file_size(filepath)
local file = io.open(filepath, "r")
if not file then
return 0
end
local size = file:seek("end")
file:close()
return size or 0
end
-- Rotate log files: log -> log.1 -> log.2 -> ... -> log.N (deleted)
function Logger:_rotate_logs()
if not self._log_file then
return false
end
local max_backups = self._config.max_backup_count or 3
-- Delete oldest backup if it exists
local oldest = self._log_file .. "." .. max_backups
if vim.fn.filereadable(oldest) == 1 then
os.remove(oldest)
end
-- Shift existing backups: .2 -> .3, .1 -> .2, etc.
for i = max_backups - 1, 1, -1 do
local old_name = self._log_file .. "." .. i
local new_name = self._log_file .. "." .. (i + 1)
if vim.fn.filereadable(old_name) == 1 then
os.rename(old_name, new_name)
end
end
-- Rotate current log to .1
if vim.fn.filereadable(self._log_file) == 1 then
os.rename(self._log_file, self._log_file .. ".1")
end
-- Write rotation marker to new log
local file = io.open(self._log_file, "w")
if file then
file:write(string.format(
"--- Log rotated at %s (previous log: %s.1) ---\n",
os.date("%Y-%m-%d %H:%M:%S"),
vim.fn.fnamemodify(self._log_file, ":t")
))
file:close()
end
self._stats.rotations = (self._stats.rotations or 0) + 1
return true
end
-- Convenience methods with early level checks to avoid function call overhead
-- when logging is filtered (common case for DEBUG in production)
function Logger:debug(message, data)
if not self._config.enabled or Logger.levels.DEBUG < self._config.level then
return
end
self:_log("DEBUG", message, data)
end
function Logger:info(message, data)
if not self._config.enabled or Logger.levels.INFO < self._config.level then
return
end
self:_log("INFO", message, data)
end
function Logger:warn(message, data)
if not self._config.enabled or Logger.levels.WARN < self._config.level then
return
end
self:_log("WARN", message, data)
self._stats.warnings_logged = self._stats.warnings_logged + 1
end
function Logger:error(message, data)
if not self._config.enabled or Logger.levels.ERROR < self._config.level then
return
end
self:_log("ERROR", message, data)
self._stats.errors_logged = self._stats.errors_logged + 1
end
function Logger:_log(level, message, data)
if not self._config.enabled then
return
end
local numeric_level = Logger.levels[level]
if numeric_level < self._config.level then
return
end
local timestamp = os.date("%Y-%m-%d %H:%M:%S")
local log_entry = {
timestamp = timestamp,
level = level,
message = message,
data = data
}
-- Add to buffer
table.insert(self._buffer, log_entry)
if #self._buffer > self._buffer_size then
table.remove(self._buffer, 1)
end
-- Format log message
local formatted_message = self:_format_message(log_entry)
-- Write to file (if we have a log file)
if self._log_file then
local self_ref = self
local ok, err = pcall(function()
vim.schedule(function()
local file = io.open(self_ref._log_file, "a")
if file then
file:write(formatted_message .. "\n")
file:close()
end
end)
end)
-- If file writing fails, we just continue without it (logging to vim messages below)
end
-- Output to vim messages for errors and warnings
if level == "ERROR" or level == "WARN" then
local vim_level = level == "ERROR" and vim.log.levels.ERROR or vim.log.levels.WARN
vim.schedule(function()
vim.notify("[diffusion] " .. message, vim_level)
end)
end
self._stats.messages_logged = self._stats.messages_logged + 1
end
function Logger:_format_message(entry)
local parts = {
entry.timestamp,
string.format("[%-5s]", entry.level),
entry.message
}
if entry.data and next(entry.data) then
parts[4] = vim.inspect(entry.data, { indent = " ", depth = 3 })
end
return table.concat(parts, " ")
end
-- Get recent log entries
function Logger:get_recent(count)
count = count or 50
local start_idx = math.max(1, #self._buffer - count + 1)
local recent = {}
for i = start_idx, #self._buffer do
table.insert(recent, vim.deepcopy(self._buffer[i]))
end
return recent
end
-- Get log file path
function Logger:get_log_file()
return self._log_file
end
-- Set log level
function Logger:set_level(level)
if type(level) == "string" then
level = Logger.levels[level]
end
if level then
self._config.level = level
end
end
-- Get current log level
function Logger:get_level()
for name, numeric_level in pairs(Logger.levels) do
if numeric_level == self._config.level then
return name
end
end
return "INFO"
end
-- Get logging statistics
function Logger:get_stats()
return vim.deepcopy(self._stats)
end
-- Clear log buffer
function Logger:clear_buffer()
self._buffer = {}
end
-- Flush logs to file immediately
function Logger:flush()
if not self._log_file then
return
end
local file = io.open(self._log_file, "a")
if not file then
return
end
for _, entry in ipairs(self._buffer) do
file:write(self:_format_message(entry) .. "\n")
end
file:close()
end
-- Get log rotation info
function Logger:get_rotation_info()
if not self._log_file then
return nil
end
local current_size = self:_get_file_size(self._log_file)
local max_size = self._config.max_file_size or (10 * 1024 * 1024)
local max_backups = self._config.max_backup_count or 3
-- Count existing backups
local backup_count = 0
local backup_sizes = {}
for i = 1, max_backups do
local backup_path = self._log_file .. "." .. i
local size = self:_get_file_size(backup_path)
if size > 0 then
backup_count = backup_count + 1
backup_sizes[i] = size
end
end
return {
log_file = self._log_file,
current_size = current_size,
current_size_human = string.format("%.2f MB", current_size / (1024 * 1024)),
max_size = max_size,
max_size_human = string.format("%.2f MB", max_size / (1024 * 1024)),
percent_full = math.floor((current_size / max_size) * 100),
max_backups = max_backups,
backup_count = backup_count,
backup_sizes = backup_sizes,
rotations_performed = self._stats.rotations or 0,
}
end
-- Manually trigger log rotation
function Logger:rotate()
if not self._log_file then
return false, "No log file configured"
end
local success = self:_rotate_logs()
if success then
return true, "Log rotated successfully"
else
return false, "Log rotation failed"
end
end
-- Create a child logger with a prefix
function Logger:child(prefix)
-- Always create children bound to the initialized singleton instance.
local parent = Logger.get()
local child = {
_parent = parent,
_prefix = prefix
}
function child:debug(message, data)
self._parent:debug(self._prefix .. ": " .. message, data)
end
function child:info(message, data)
self._parent:info(self._prefix .. ": " .. message, data)
end
function child:warn(message, data)
self._parent:warn(self._prefix .. ": " .. message, data)
end
function child:error(message, data)
self._parent:error(self._prefix .. ": " .. message, data)
end
function child:log_buffer_state(context, level)
-- Prepend prefix to context and delegate to parent
return self._parent:log_buffer_state(self._prefix .. ": " .. context, level)
end
function child:child(suffix)
return self._parent:child(self._prefix .. "/" .. tostring(suffix))
end
return child
end
-- Log all open buffers with detailed information
function Logger:log_buffer_state(context, level)
level = level or "DEBUG"
local buffers = {}
-- Safely get current buffer - may fail in fast event context
local current_buf = nil
local success, buf = pcall(vim.api.nvim_get_current_buf)
if success then
current_buf = buf
end
-- Get all loaded buffers (with fast context protection)
local success, all_bufs = pcall(vim.api.nvim_list_bufs)
if not success then
-- In fast context, skip buffer logging
self:_log(level, context .. " [SKIPPED - fast context]", {
current_buf = current_buf,
error = "fast context"
})
return
end
for _, buf in ipairs(all_bufs) do
local is_loaded = pcall(vim.api.nvim_buf_is_loaded, buf)
if is_loaded then
local buf_name = vim.api.nvim_buf_get_name(buf)
local buf_type = vim.api.nvim_buf_get_option(buf, 'buftype')
local filetype = vim.api.nvim_buf_get_option(buf, 'filetype')
local modified = vim.api.nvim_buf_get_option(buf, 'modified')
local listed = vim.api.nvim_buf_get_option(buf, 'buflisted')
-- Check if buffer is visible in any window
local visible_windows = {}
local wins_success, all_wins = pcall(vim.api.nvim_list_wins)
if wins_success then
for _, win in ipairs(all_wins) do
local win_buf_success, win_buf = pcall(vim.api.nvim_win_get_buf, win)
if win_buf_success and win_buf == buf then
table.insert(visible_windows, win)
end
end
end
table.insert(buffers, {
id = buf,
name = buf_name,
type = buf_type,
filetype = filetype,
modified = modified,
listed = listed,
is_current = buf == current_buf,
visible_windows = visible_windows,
window_count = #visible_windows
})
end
end
local buffer_summary = {
total_buffers = #buffers,
current_buffer = current_buf,
context = context,
timestamp = os.date("%Y-%m-%d %H:%M:%S.%03d", os.time()),
buffers = buffers
}
self:_log(level, "Buffer state snapshot: " .. context, buffer_summary)
return buffer_summary
end
-- Global logger access
function Logger.get()
if not Logger._instance then
return Logger:setup({})
end
return Logger._instance
end
return Logger