Advertisement
Guest User

mlog.lua

a guest
Jan 22nd, 2020
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.50 KB | None | 0 0
  1. local filesystem = require("filesystem")
  2. require("util")
  3.  
  4. local mlog = {}
  5. local logDir = "/var/log"
  6. local config = {}
  7.  
  8. -- TODO should have individual configurable logging instances
  9.  
  10. ----------------------
  11. -- log levels
  12. -- 0 = OFF
  13. -- 1 = ERROR
  14. -- 2 = WARNING
  15. -- 3 = NOTICE
  16. -- 4 = DEBUG
  17.  
  18. config.level = 3 -- default to NOTICE, supress DEBUG
  19. config.logFile = "messages" -- default log file
  20. mlog.config = config
  21.  
  22. function mlog.log(msg, level)
  23.   if level > config.level then
  24.     return
  25.   end
  26.  
  27.   local color = solarized.fg
  28.   if level == 4 then
  29.     color = solarized.blue
  30.   elseif level == 2 then
  31.     color = solarized.yellow
  32.   elseif level == 1 then
  33.     color = solarized.red
  34.   end
  35.  
  36.   -- TODO cache file streams
  37.   local logPath = logDir .. "/" .. config.logFile
  38.   local file = filesystem.open(logPath, "a")
  39.   if not file then
  40.     error("Failed to open to log file: " .. logPath)
  41.    
  42.   end
  43.   local timestamp = os.date()
  44.   local success = file:write(timestamp .. " : " .. msg .. "\n")
  45.   file:close()
  46.   if not success then
  47.     error("Failed to write to log file: " .. logPath)
  48.   end
  49.   printC(os.date(), solarized.green)
  50.   printC(" : " .. msg, color)
  51.   print()
  52.  
  53. end
  54.  
  55. function mlog.info(msg)
  56.   mlog.log(msg, 3)
  57. end
  58.  
  59. function mlog.error(msg)
  60.   mlog.log(msg, 1)
  61. end
  62.  
  63. function mlog.warning(msg)
  64.   mlog.log(msg, 2)
  65. end
  66.  
  67. function mlog.debug(msg)
  68.   mlog.log(msg, 4)
  69. end
  70.  
  71. -- internal function for initializing the logger
  72. function init()
  73.   if not filesystem.isDirectory(logDir) then
  74.     filesystem.makeDirectory(logDir)
  75.   end
  76. end
  77.  
  78.  
  79. init()
  80.  
  81. return mlog
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement