log.lua 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. local Log = {}
  2. --- Creates a log handle based on Plenary.log
  3. ---@param opts these are passed verbatim to Plenary.log
  4. ---@return log handle
  5. function Log:new(opts)
  6. local status_ok, handle = pcall(require, "plenary.log")
  7. if not status_ok then
  8. vim.notify("Plenary.log is not available. Logging to console only", vim.log.levels.DEBUG)
  9. end
  10. self.__handle = handle
  11. local path = string.format("%s/%s.log", vim.api.nvim_call_function("stdpath", { "cache" }), opts.plugin)
  12. self.get_path = function()
  13. return path
  14. end
  15. setmetatable({}, Log)
  16. return self
  17. end
  18. function Log:add_entry(msg, level)
  19. local status_ok, _ = pcall(require, "plenary.log")
  20. if not status_ok then
  21. return vim.notify(msg, vim.log.levels[level])
  22. end
  23. -- plenary uses lower-case log levels
  24. return self.__handle[level:lower()](msg)
  25. end
  26. --- Creates or retrieves a log handle for the default logfile
  27. --- based on Plenary.log
  28. ---@return log handle
  29. function Log:new_default()
  30. return Log:new { plugin = "lunarvim", level = lvim.log.level }
  31. end
  32. function Log:trace(msg)
  33. self:add_entry(msg, "TRACE")
  34. end
  35. function Log:debug(msg)
  36. self:add_entry(msg, "DEBUG")
  37. end
  38. function Log:info(msg)
  39. self:add_entry(msg, "INFO")
  40. end
  41. function Log:warn(msg)
  42. self:add_entry(msg, "TRACE")
  43. end
  44. function Log:error(msg)
  45. self:add_entry(msg, "TRACE")
  46. end
  47. return Log