lua-rtos-libs/libs/logger.lua

59 lines
1.6 KiB
Lua

local function new(template, maxLines, maxFiles, timeFormat, timeOffset)
local template = template or "/public/logfile_%.log"
local maxLines = maxLines or 100
local maxFiles = maxFiles or 3
local timeFormat = timeFormat or "[%Y-%m-%d %H:%M:%S]"
local currentFile = 1
local currentLine = 0
local function init()
for i = 1, maxFiles do
local fileName = template:gsub("%%", i)
local file = io.open(fileName, "r")
if file then
local lines = 0
for line in file:lines() do
lines = lines + 1
end
file:close()
if lines < maxLines then
currentFile = i
currentLine = lines
break
end
else
currentFile = i
break
end
end
end
local function rotateFile()
currentFile = currentFile % maxFiles + 1
currentLine = 0
local fileName = template:gsub("%%", currentFile)
os.remove(fileName)
end
local function write(line)
if currentLine >= maxLines then
rotateFile()
end
local fileName = template:gsub("%%", currentFile)
local file = io.open(fileName, "a")
if not file then
print("Failed to open file: " .. fileName)
return
end
file:write(os.date(timeFormat) .. " " .. line .. "\n")
file:close()
currentLine = currentLine + 1
end
init()
return write
end
return new