modlib/log.lua

73 lines
1.9 KiB
Lua
Raw Normal View History

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