modlib/log.lua

87 lines
2.0 KiB
Lua
Raw Normal View History

-- Localize globals
local ipairs, minetest, modlib, os, pairs, table = ipairs, minetest, modlib, os, pairs, table
2021-06-17 10:45:08 -07:00
-- Set environment
local _ENV = {}
setfenv(1, _ENV)
2020-02-08 16:39:54 -08:00
-- Log helpers - write to log, force writing to file
2020-02-13 02:11:52 -08:00
minetest.mkdir(minetest.get_worldpath() .. "/logs")
channels = {}
last_day = os.date("%d")
2020-02-08 16:39:54 -08:00
function get_path(logname)
2021-03-27 12:10:49 -07:00
return minetest.get_worldpath() .. "/logs/" .. logname
2020-02-08 16:39:54 -08:00
end
function create_channel(title)
2021-03-27 12:10:49 -07:00
local dir = get_path(title)
minetest.mkdir(dir)
channels[title] = {dirname = dir, queue = {}}
write(title, "Initialisation")
2020-02-08 16:39:54 -08:00
end
function write(channelname, msg)
2021-03-27 12:10:49 -07:00
local channel = channels[channelname]
local current_day = os.date("%d")
if current_day ~= last_day then
last_day = current_day
write_to_file(channelname, channel, os.date("%Y-%m-%d"))
end
table.insert(channel.queue, os.date("[%H:%M:%S] ") .. msg)
2020-02-08 16:39:54 -08:00
end
function write_to_all(msg)
2021-03-27 12:10:49 -07:00
for channelname, _ in pairs(channels) do
write(channelname, msg)
end
2020-02-08 16:39:54 -08:00
end
function write_to_file(name, channel, current_date)
2021-03-27 12:10:49 -07:00
if not channel then
channel = channels[name]
end
if #(channel.queue) > 0 then
local filename = channel.dirname .. "/" .. (current_date or os.date("%Y-%m-%d")) .. ".txt"
local rope = {}
for _, msg in ipairs(channel.queue) do
table.insert(rope, msg)
end
modlib.file.append(filename, table.concat(rope, "\n") .. "\n")
channels[name].queue = {}
end
2020-02-08 16:39:54 -08:00
end
function write_all_to_file()
2021-03-27 12:10:49 -07:00
local current_date = os.date("%Y-%m-%d")
for name, channel in pairs(channels) do
write_to_file(name, channel, current_date)
end
2020-02-08 16:39:54 -08:00
end
2020-03-13 10:13:45 -07:00
function write_safe(channelname, msg)
2021-03-27 12:10:49 -07:00
write(channelname, msg)
write_all_to_file()
2020-03-13 10:13:45 -07:00
end
2020-02-08 16:39:54 -08:00
2020-02-13 02:11:52 -08:00
local timer = 0
2020-02-08 16:39:54 -08:00
2020-02-13 02:11:52 -08:00
minetest.register_globalstep(
2021-03-27 12:10:49 -07:00
function(dtime)
timer = timer + dtime
if timer > 5 then
write_all_to_file()
timer = 0
end
end
2020-02-13 02:11:52 -08:00
)
2020-02-08 16:39:54 -08:00
2020-02-13 02:11:52 -08:00
minetest.register_on_mods_loaded(
2021-03-27 12:10:49 -07:00
function()
write_to_all("Mods loaded")
end
2020-02-13 02:11:52 -08:00
)
2020-02-08 16:39:54 -08:00
2020-02-13 02:11:52 -08:00
minetest.register_on_shutdown(
2021-03-27 12:10:49 -07:00
function()
write_to_all("Shutdown")
write_all_to_file()
end
2020-02-13 02:11:52 -08:00
)
2021-06-17 10:45:08 -07:00
-- Export environment
return _ENV