robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
7.8 KiB279 linesraw
1--- @brief
2---
3--- The |vim.log| module provides file-backed logger instances.
4---
5--- Use `vim.log.new()` to create a logger, it exposes five writer functions:
6--- `trace()`, `debug()`, `info()`, `warn()`, and `error()`.
7--- They are correspond to log levels defined by |vim.log.levels|.
8---
9--- Example:
10---
11--- ```lua
12--- local log = vim.log.new({ name = 'my-plugin', })
13--- -- By default, logs will be written to {name}.log under `stdpath('log')`.
14---
15--- log.error('request failed', 'timeout')
16--- -- This will write a line like the following to the log file:
17--- --   [ERROR][2024-01-01 12:00:00] source.lua:123    request failed    timeout
18---
19--- -- Set the log level to `INFO`, otherwise the `info()` call below would be ignored,
20--- -- since the default level is `WARN`.
21--- vim.log.set_level(log, vim.log.levels.INFO)
22--- log.info('starting', { buf = vim.api.nvim_get_current_buf() })
23--- -- This will write a line like the following to the log file:
24--- --   [INFO][2024-01-01 12:01:00] source.lua:124    starting    { buf = 1 }
25--- ```
26---
27--- You can also provide a custom formatter function to customize the log output format.
28
29---@class vim.Log
30---
31--- Display name used in notifications emitted by the logger.
32---@field private name string
33---
34--- Minimum level that will be written.
35---@field private level integer
36---
37--- Function used to format a log entry.
38---@field private format_func fun(min_level: vim.log.levels, level: vim.log.levels, ...): string?
39---
40--- Path of the log file.
41---@field private filename string
42---
43--- Internal state for the log file handle. `nil` until the file is opened.
44---@field private logfile file?
45---
46--- Internal state for the log file open error.
47---@field private openerr string?
48---
49--- Writes a message at `vim.log.levels.TRACE`.
50---@field trace fun(...:any): boolean?
51---
52--- Writes a message at `vim.log.levels.DEBUG`.
53---@field debug fun(...:any): boolean?
54---
55--- Writes a message at `vim.log.levels.INFO`.
56---@field info fun(...:any): boolean?
57---
58--- Writes a message at `vim.log.levels.WARN`.
59---@field warn fun(...:any): boolean?
60---
61--- Writes a message at `vim.log.levels.ERROR`.
62---@field error fun(...:any): boolean?
63local M = {}
64
65---@enum vim.log.levels
66---@nodoc
67M.levels = {
68  TRACE = 0,
69  DEBUG = 1,
70  INFO = 2,
71  WARN = 3,
72  ERROR = 4,
73  OFF = 5,
74}
75
76local level_names = {
77  [0] = 'TRACE',
78  [1] = 'DEBUG',
79  [2] = 'INFO',
80  [3] = 'WARN',
81  [4] = 'ERROR',
82  [5] = 'OFF',
83}
84
85local log_date_format = '%F %H:%M:%S'
86
87--- Default formatter used by |vim.log.new()|.
88---
89--- Formats a message as:
90--- `[LEVEL][YYYY-MM-DD HH:MM:SS] source.lua:line<TAB>arg1<TAB>arg2`
91---
92---@param min_level vim.log.levels
93---@param level vim.log.levels
94---@return string?
95local function default_format_func(min_level, level, ...)
96  if level < min_level then
97    return nil
98  end
99
100  -- Stack shape:
101  --   default_format_func <- create_writer closure <- user callsite
102  local info = debug.getinfo(3, 'Sl')
103  local header = string.format(
104    '[%s][%s] %s:%s',
105    level_names[level],
106    os.date(log_date_format),
107    info and info.short_src or '?',
108    info and info.currentline or -1
109  )
110  local parts = { header }
111  local argc = select('#', ...)
112  for i = 1, argc do
113    local arg = select(i, ...)
114    table.insert(parts, arg == nil and 'nil' or vim.inspect(arg, { newline = ' ', indent = '' }))
115  end
116  return table.concat(parts, '\t') .. '\n'
117end
118
119---@class vim.log.new.Opts
120---@inlinedoc
121---
122--- Display name used in notifications emitted by the logger.
123---@field name string
124---
125--- Minimum level that will be written.
126--- (default: `vim.log.levels.WARN`)
127---@field level? vim.log.levels
128---
129--- Formatter used for each log entry.
130--- Receives the logger's minimum level, the message level, and the values passed to the writer.
131--- Return a string to write an entry, or `nil` to skip it.
132---@field format_func? fun(min_level: vim.log.levels, level: vim.log.levels, ...): string?
133
134--- Creates a logger instance.
135---
136--- The logger writes formatted messages to a file,
137--- using a per-instance log level and formatting function.
138---
139---@param opts vim.log.new.Opts
140---@return vim.Log
141function M.new(opts)
142  vim.validate('opts', opts, 'table')
143  vim.validate('opts.name', opts.name, 'string')
144  vim.validate('opts.level', opts.level, 'number', true)
145  vim.validate('opts.format_func', opts.format_func, 'function', true)
146
147  local filename = vim.fs.joinpath(vim.fn.stdpath('log'), opts.name:lower() .. '.log')
148  local log_dir = vim.fs.dirname(filename)
149  if log_dir then
150    -- TODO: Ideally, directory creation should be delayed until open_file(), right before
151    -- opening the log file, but open() can be called from libuv callbacks,
152    -- where using fn.mkdir() is not allowed.
153    vim.fn.mkdir(log_dir, 'p')
154  end
155
156  local log = setmetatable({
157    name = opts.name,
158    filename = filename,
159    level = opts.level or M.levels.WARN,
160    format_func = opts.format_func or default_format_func,
161  }, { __index = M })
162  log.trace = log:create_writer(M.levels.TRACE)
163  log.debug = log:create_writer(M.levels.DEBUG)
164  log.info = log:create_writer(M.levels.INFO)
165  log.warn = log:create_writer(M.levels.WARN)
166  log.error = log:create_writer(M.levels.ERROR)
167
168  return log
169end
170
171---@param msg string
172---@param level? vim.log.levels
173local function notify(msg, level)
174  if vim.in_fast_event() then
175    vim.schedule(function()
176      vim.notify(msg, level)
177    end)
178  else
179    vim.notify(msg, level)
180  end
181end
182
183--- Opens the log file on first use.
184---
185--- Writes a `[START]` marker when the file is opened successfully.
186---
187---@package
188---@return boolean # `true` if the file is open, `false` on error.
189function M:open_file()
190  if self.logfile then
191    return true
192  end
193  if self.openerr then
194    return false
195  end
196
197  self.logfile, self.openerr = io.open(self.filename, 'a+')
198  if not self.logfile then
199    local err_msg = string.format('Failed to open %s log file: %s', self.name, self.openerr)
200    notify(err_msg, M.levels.ERROR)
201    return false
202  end
203
204  local log_info = vim.uv.fs_stat(self.filename)
205  if log_info and log_info.size > 1e9 then
206    local warn_msg = string.format(
207      '%s log is large (%d MB): %s',
208      self.name,
209      log_info.size / (1000 * 1000),
210      self.filename
211    )
212    notify(warn_msg)
213  end
214
215  -- Start message for logging
216  self.logfile:write(
217    string.format('[START][%s] %s logging initiated\n', os.date(log_date_format), self.name)
218  )
219  return true
220end
221
222--- Creates a writer function for a specific log level.
223---
224---@package
225---@param level vim.log.levels
226---@return fun(...:any): boolean? # Returns `false` if the log file could not be opened.
227function M:create_writer(level)
228  return function(...)
229    local argc = select('#', ...)
230    if argc == 0 then
231      return true
232    end
233    if not self:open_file() then
234      return false
235    end
236    local message = self.format_func(self.level, level, ...)
237    if message then
238      assert(self.logfile)
239      self.logfile:write(message)
240      self.logfile:flush()
241    end
242  end
243end
244
245--- Sets the current log level.
246---
247--- Entries below this level are skipped.
248---
249---@param log vim.Log
250---@param level vim.log.levels
251function M.set_level(log, level)
252  vim.validate('level', level, 'number')
253  log.level = level
254end
255
256--- Gets the current log level.
257---@param log vim.Log
258---@return vim.log.levels
259function M.get_level(log)
260  return log.level
261end
262
263--- Sets the formatter used to produce log entries.
264---
265--- The formatter receives the logger's minimum level, the message level,
266--- and the values passed to the writer method.
267--- Return a string to write an entry, or `nil` to skip it.
268---
269---@param log vim.Log
270---@param func fun(min_level: vim.log.levels, level: vim.log.levels, ...): string?
271function M.set_format_func(log, func)
272  vim.validate('func', func, function(f)
273    return type(f) == 'function' or f == vim.inspect
274  end, false, 'func must be a function')
275
276  log.format_func = func
277end
278
279return M