log.lua (6605B)
1 --- @brief 2 --- The `vim.lsp.log` module provides logging for the Nvim LSP client. 3 --- 4 --- When debugging language servers, it is helpful to enable extra-verbose logging of the LSP client 5 --- RPC events. Example: 6 --- ```lua 7 --- vim.lsp.log.set_level 'trace' 8 --- require('vim.lsp.log').set_format_func(vim.inspect) 9 --- ``` 10 --- 11 --- Then try to run the language server, and open the log with: 12 --- ```vim 13 --- :lua vim.cmd('tabnew ' .. vim.lsp.log.get_filename()) 14 --- ``` 15 --- 16 --- (Or use `:LspLog` if you have nvim-lspconfig installed.) 17 --- 18 --- Note: 19 --- - Remember to DISABLE verbose logging ("debug" or "trace" level), else you may encounter 20 --- performance issues. 21 --- - "ERROR" messages containing "stderr" only indicate that the log was sent to stderr. Many 22 --- servers send harmless messages via stderr. 23 24 local log = {} 25 26 local log_levels = vim.log.levels 27 28 local protocol = require('vim.lsp.protocol') 29 30 --- Log level dictionary with reverse lookup as well. 31 --- 32 --- Can be used to lookup the number from the name or the name from the number. 33 --- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "OFF" 34 --- Level numbers begin with "TRACE" at 0 35 --- @type table<string,integer> | table<integer, string> 36 --- @nodoc 37 log.levels = vim.deepcopy(log_levels) 38 39 -- Default log level is warn. 40 local current_log_level = log_levels.WARN 41 42 local log_date_format = '%F %H:%M:%S' 43 44 --- Default formatting function. 45 --- @param level? string 46 local function format_func(level, ...) 47 if log_levels[level] < current_log_level then 48 return nil 49 end 50 51 local info = debug.getinfo(2, 'Sl') 52 local header = string.format( 53 '[%s][%s] %s:%s', 54 level, 55 os.date(log_date_format), 56 info.short_src, 57 info.currentline 58 ) 59 local parts = { header } 60 local argc = select('#', ...) 61 for i = 1, argc do 62 local arg = select(i, ...) 63 table.insert(parts, arg == nil and 'nil' or vim.inspect(arg, { newline = ' ', indent = '' })) 64 end 65 return table.concat(parts, '\t') .. '\n' 66 end 67 68 local function notify(msg, level) 69 if vim.in_fast_event() then 70 vim.schedule(function() 71 vim.notify(msg, level) 72 end) 73 else 74 vim.notify(msg, level) 75 end 76 end 77 78 local logfilename = vim.fs.joinpath(vim.fn.stdpath('log') --[[@as string]], 'lsp.log') 79 80 -- TODO: Ideally the directory should be created in open_logfile(), right 81 -- before opening the log file, but open_logfile() can be called from libuv 82 -- callbacks, where using fn.mkdir() is not allowed. 83 vim.fn.mkdir(vim.fn.stdpath('log') --[[@as string]], 'p') 84 85 --- Returns the log filename. 86 ---@return string log filename 87 function log.get_filename() 88 return logfilename 89 end 90 91 --- @param s string 92 function log._set_filename(s) 93 logfilename = s 94 end 95 96 --- @type file*?, string? 97 local logfile, openerr 98 99 --- Opens log file. Returns true if file is open, false on error 100 local function open_logfile() 101 -- Try to open file only once 102 if logfile then 103 return true 104 end 105 if openerr then 106 return false 107 end 108 109 logfile, openerr = io.open(logfilename, 'a+') 110 if not logfile then 111 local err_msg = string.format('Failed to open LSP client log file: %s', openerr) 112 notify(err_msg, log_levels.ERROR) 113 return false 114 end 115 116 local log_info = vim.uv.fs_stat(logfilename) 117 if log_info and log_info.size > 1e9 then 118 local warn_msg = string.format( 119 'LSP client log is large (%d MB): %s', 120 log_info.size / (1000 * 1000), 121 logfilename 122 ) 123 notify(warn_msg) 124 end 125 126 -- Start message for logging 127 logfile:write(string.format('[START][%s] LSP logging initiated\n', os.date(log_date_format))) 128 return true 129 end 130 131 for level, levelnr in pairs(log_levels) do 132 -- Also export the log level on the root object. 133 ---@diagnostic disable-next-line: no-unknown 134 log[level] = levelnr 135 136 -- Add a reverse lookup. 137 log.levels[levelnr] = level 138 end 139 140 --- @param level string 141 --- @return fun(...:any): boolean? 142 local function create_logger(level) 143 return function(...) 144 local argc = select('#', ...) 145 if argc == 0 then 146 return true 147 end 148 if not open_logfile() then 149 return false 150 end 151 local message = format_func(level, ...) 152 if message then 153 assert(logfile) 154 logfile:write(message) 155 logfile:flush() 156 end 157 end 158 end 159 160 -- If called without arguments, it will check whether the log level is 161 -- greater than or equal to this one. When called with arguments, it will 162 -- log at that level (if applicable, it is checked either way). 163 164 --- @nodoc 165 log.debug = create_logger('DEBUG') 166 167 --- @nodoc 168 log.error = create_logger('ERROR') 169 170 --- @nodoc 171 log.info = create_logger('INFO') 172 173 --- @nodoc 174 log.trace = create_logger('TRACE') 175 176 --- @nodoc 177 log.warn = create_logger('WARN') 178 179 --- Sets the current log level. 180 ---@param level (string|integer) One of |vim.log.levels| 181 function log.set_level(level) 182 vim.validate('level', level, { 'string', 'number' }) 183 184 if type(level) == 'string' then 185 current_log_level = 186 assert(log.levels[level:upper()], string.format('Invalid log level: %q', level)) 187 else 188 assert(log.levels[level], string.format('Invalid log level: %d', level)) 189 current_log_level = level 190 end 191 end 192 193 --- Gets the current log level. 194 ---@return integer current log level 195 function log.get_level() 196 return current_log_level 197 end 198 199 --- Sets the formatting function used to format logs. If the formatting function returns nil, the entry won't 200 --- be written to the log file. 201 ---@param handle fun(level:string, ...): string? Function to apply to log entries. The default will log the level, 202 ---date, source and line number of the caller, followed by the arguments. 203 function log.set_format_func(handle) 204 vim.validate('handle', handle, function(h) 205 return type(h) == 'function' or h == vim.inspect 206 end, false, 'handle must be a function') 207 208 format_func = handle 209 end 210 211 --- Checks whether the level is sufficient for logging. 212 ---@deprecated 213 ---@param level integer log level 214 ---@return boolean : true if would log, false if not 215 function log.should_log(level) 216 vim.deprecate('vim.lsp.log.should_log', 'vim.lsp.log.set_format_func', '0.13') 217 218 vim.validate('level', level, 'number') 219 220 return level >= current_log_level 221 end 222 223 --- Convert LSP MessageType to vim.log.levels 224 --- 225 ---@param message_type lsp.MessageType 226 function log._from_lsp_level(message_type) 227 if message_type == protocol.MessageType.Error then 228 return log_levels.ERROR 229 elseif message_type == protocol.MessageType.Warning then 230 return log_levels.WARN 231 elseif message_type == protocol.MessageType.Info or message_type == protocol.MessageType.Log then 232 return log_levels.INFO 233 else 234 return log_levels.DEBUG 235 end 236 end 237 238 return log