modlib/log.lua

87 lines
2.0 KiB
Lua
Raw Permalink Normal View History

-- Localize globals
local ipairs, minetest, modlib, os, pairs, table = ipairs, minetest, modlib, os, pairs, table
2021-06-17 19:45:08 +02:00
-- Set environment
local _ENV = {}
setfenv(1, _ENV)
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)
2021-03-27 20:10:49 +01:00
return minetest.get_worldpath() .. "/logs/" .. logname
2020-02-09 01:39:54 +01:00
end
function create_channel(title)
2021-03-27 20:10:49 +01:00
local dir = get_path(title)
minetest.mkdir(dir)
channels[title] = {dirname = dir, queue = {}}
write(title, "Initialisation")
2020-02-09 01:39:54 +01:00
end
function write(channelname, msg)
2021-03-27 20:10:49 +01: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-09 01:39:54 +01:00
end
function write_to_all(msg)
2021-03-27 20:10:49 +01:00
for channelname, _ in pairs(channels) do
write(channelname, msg)
end
2020-02-09 01:39:54 +01:00
end
function write_to_file(name, channel, current_date)
2021-03-27 20:10:49 +01: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-09 01:39:54 +01:00
end
function write_all_to_file()
2021-03-27 20:10:49 +01: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-09 01:39:54 +01:00
end
2020-03-13 18:13:45 +01:00
function write_safe(channelname, msg)
2021-03-27 20:10:49 +01:00
write(channelname, msg)
write_all_to_file()
2020-03-13 18:13:45 +01:00
end
2020-02-09 01:39:54 +01:00
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(
2021-03-27 20:10:49 +01:00
function(dtime)
timer = timer + dtime
if timer > 5 then
write_all_to_file()
timer = 0
end
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(
2021-03-27 20:10:49 +01:00
function()
write_to_all("Mods loaded")
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_shutdown(
2021-03-27 20:10:49 +01:00
function()
write_to_all("Shutdown")
write_all_to_file()
end
2020-02-13 11:11:52 +01:00
)
2021-06-17 19:45:08 +02:00
-- Export environment
return _ENV