robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ={ 68TRACE =0 , 69DEBUG =1 , 70INFO =2 , 71WARN =3 , 72ERROR =4 , 73OFF =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 , ... ) 96if level < min_level then 97return nil 98end 99 100-- Stack shape: 101-- default_format_func <- create_writer closure <- user callsite 102local info =debug . getinfo ( 3 , 'Sl' ) 103local header =string . format ( 104'[%s][%s] %s:%s' , 105level_names [ level ], 106os . date ( log_date_format ), 107info and info . short_src or '?' , 108info and info . currentline or - 1 109) 110local parts ={ header } 111local argc =select ( '#' , ... ) 112for i =1 , argc do 113local arg =select ( i , ... ) 114table . insert ( parts , arg == nil and 'nil' or vim . inspect ( arg , { newline =' ' , indent ='' } )) 115end 116return 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 ) 142vim . validate ( 'opts' , opts , 'table' ) 143vim . validate ( 'opts.name' , opts . name , 'string' ) 144vim . validate ( 'opts.level' , opts . level , 'number' , true ) 145vim . validate ( 'opts.format_func' , opts . format_func , 'function' , true ) 146 147local filename =vim . fs . joinpath ( vim . fn . stdpath ( 'log' ), opts . name : lower () .. '.log' ) 148local log_dir =vim . fs . dirname ( filename ) 149if 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. 153vim . fn . mkdir ( log_dir , 'p' ) 154end 155 156local log =setmetatable ( { 157name =opts . name , 158filename =filename , 159level =opts . level or M . levels . WARN , 160format_func =opts . format_func or default_format_func , 161} , { __index =M } ) 162log . trace =log : create_writer ( M . levels . TRACE ) 163log . debug =log : create_writer ( M . levels . DEBUG ) 164log . info =log : create_writer ( M . levels . INFO ) 165log . warn =log : create_writer ( M . levels . WARN ) 166log . error =log : create_writer ( M . levels . ERROR ) 167 168return log 169end 170 171---@param msg string 172---@param level? vim.log.levels 173local function notify ( msg , level ) 174if vim . in_fast_event () then 175vim . schedule ( function () 176vim . notify ( msg , level ) 177end ) 178else 179vim . notify ( msg , level ) 180end 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 () 190if self . logfile then 191return true 192end 193if self . openerr then 194return false 195end 196 197self . logfile , self . openerr =io . open ( self . filename , 'a+' ) 198if not self . logfile then 199local err_msg =string . format ( 'Failed to open %s log file: %s' , self . name , self . openerr ) 200notify ( err_msg , M . levels . ERROR ) 201return false 202end 203 204local log_info =vim . uv . fs_stat ( self . filename ) 205if log_info and log_info . size > 1e9 then 206local warn_msg =string . format ( 207'%s log is large (%d MB): %s' , 208self . name , 209log_info . size / ( 1000 * 1000 ), 210self . filename 211) 212notify ( warn_msg ) 213end 214 215-- Start message for logging 216self . logfile : write ( 217string . format ( '[START][%s] %s logging initiated\n' , os . date ( log_date_format ), self . name ) 218) 219return 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 ) 228return function ( ... ) 229local argc =select ( '#' , ... ) 230if argc == 0 then 231return true 232end 233if not self : open_file () then 234return false 235end 236local message =self . format_func ( self . level , level , ... ) 237if message then 238assert ( self . logfile ) 239self . logfile : write ( message ) 240self . logfile : flush () 241end 242end 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 ) 252vim . validate ( 'level' , level , 'number' ) 253log . 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 ) 260return 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 ) 272vim . validate ( 'func' , func , function ( f ) 273return type ( f ) == 'function' or f == vim . inspect 274end , false , 'func must be a function' ) 275 276log . format_func =func 277end 278 279return M