Add structured logging functionality to enhance debugging capabilities

This commit is contained in:
MayaTheShy
2026-03-22 01:59:15 -04:00
parent 0e4d184059
commit 71db1d9973

45
lib/log.lua Normal file
View File

@@ -0,0 +1,45 @@
-- lib/log.lua — Structured logging for CC:Tweaked programs
-- Usage:
-- local log = dofile("lib/log.lua")
-- log.info("SMELT", "Loaded %d recipes", count)
-- log.warn("NET", "No modem found")
-- log.setLevel("DEBUG") -- show everything
--
-- Levels: DEBUG < INFO < WARN < ERROR
-- Default level: INFO (suppresses DEBUG)
local LEVELS = { DEBUG = 1, INFO = 2, WARN = 3, ERROR = 4 }
local minLevel = LEVELS.INFO
local log = {}
--- Set minimum log level (string: "DEBUG", "INFO", "WARN", "ERROR")
function log.setLevel(level)
minLevel = LEVELS[level] or LEVELS.INFO
end
--- Get the current minimum level name
function log.getLevel()
for name, val in pairs(LEVELS) do
if val == minLevel then return name end
end
return "INFO"
end
local function emit(levelName, tag, msg, ...)
if LEVELS[levelName] < minLevel then return end
local text
if select("#", ...) > 0 then
text = string.format(msg, ...)
else
text = msg
end
print(string.format("[%s][%s] %s", levelName, tag, text))
end
function log.debug(tag, msg, ...) emit("DEBUG", tag, msg, ...) end
function log.info(tag, msg, ...) emit("INFO", tag, msg, ...) end
function log.warn(tag, msg, ...) emit("WARN", tag, msg, ...) end
function log.error(tag, msg, ...) emit("ERROR", tag, msg, ...) end
return log