-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog.lua
More file actions
88 lines (76 loc) · 2.4 KB
/
log.lua
File metadata and controls
88 lines (76 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
---@class Log
Log = {}
-- All IO Log writing should be handled here
--- settings Used:
--- MaxFileLength & ErrorFile
local errorFilePath
local maxFileLength
local function getMaxFileLength()
if maxFileLength ~= nil then return maxFileLength end
if not pcall(function()
maxFileLength = settings.get("MaxFileLength", 10000)
end) then
maxFileLength = 10000
end
return maxFileLength
end
---@param file file*?
---@param content string | number | table Content to fill the File with
local function write(file, content, filePath)
local c
if type(content) == "table" then
c = textutils.serialise(content);
else
c = content
end
-- if over MaxFileLength, override all
local size = file:seek("end")
size = size or 0
if size > getMaxFileLength() then
print("Size", size)
file:close();
io.open(filePath, "w+")
end
---@diagnostic disable-next-line: need-check-nil
file:write(c .. os.date(("[%Y-%m-%d %H:%M:%S] ")));
---@diagnostic disable-next-line: need-check-nil
file:close();
end
local function getErrorFile()
if errorFilePath ~= nil then return errorFilePath end
if not pcall(function()
errorFilePath = settings.set("ErrorFile", "Logs/Errors.lua")
end) then
errorFilePath = "Logs/Errors.lua"
end
return errorFilePath
end
---Log Write...
---@param filePath string Path incl. Filename
---@param content string | number | table Content to fill the File with
---@param dataAccess string How to access the File ("w", "w+", "a", "a+")
function Log.write(content, filePath, dataAccess)
dataAccess = dataAccess or "w+"
local file = io.open(filePath, dataAccess);
if file == nil then
Log.ErrorHandler("\nCould not open to File: \"" .. filePath .. "\"", nil, true);
return
end
local succ, err = pcall(function() write(file, content, filePath) end)
if not succ then
Log.ErrorHandler(err, nil, true)
end
end
---@param content string
---@param filePath string | nil
---@param traceback boolean | nil
function Log.ErrorHandler(content, filePath, traceback)
filePath = filePath or getErrorFile();
local errorFile = io.open(filePath, "a+")
if traceback then
content = debug.traceback(content);
end
local succ, err = pcall(function() write(errorFile, content, filePath) end)
if not succ then error(err) end
end
return Log