Page 1 of 1

Error logger

Posted: Tue Apr 23, 2013 10:01 am
by rk84
pcall is helpfull, if for example you add new mod that depend on some other mod and order of mod list is wrong and game abort in startup. But since I wanted to get notes of errors pcall catches, I made logger. Mayby a bit late post since next release (0.4) will add dependencies for mods. But there might be some use for it.

pros: Logger might be usefull if you want to avoid errors and still get log of those errors.
cons: Game keeps running and the problem might migrate to later parts of code creating confusion, if you don't check the log.

In code below, saferequire() is used like require. It calls require within pcall. pcall catches the error and returns status boolean and error string. Error message is then written in text file named "modlogs.txt" in same folder as Factorio.exe.

Example usage. Code from one of my mods.

Code: Select all

--ccmod\data.lua
require("prototypes.ammo-categories")
require("prototypes.entities")
require("prototypes.items")
require("prototypes.recipe-categories")
require("prototypes.recipes")
require("prototypes.technology")

local i = string.find(debug.getinfo(1).source, "Factorio") or 1
local path = string.sub(debug.getinfo(1).source, i) .. " "					-- Cuts the path to sourcefile
logfile = assert( io.open("modlogs.txt" , "a+"), "Cannot open the file.")	-- Greating/Opening logfile. "a+" writing only at the end of file.
logfile:write(path, os.date("%d.%m.%Y %H:%M"), "\n")						-- Writing sourcefile path & timestamp

function saferequire(file)
	local status, err = pcall(require, file)
	if not status then
		logfile:write(err, "\n")
	end
end

saferequire("prototypes.repairtech")			--requires Repairtool mod
saferequire("prototypes.fstech")			--requires Freight Station Mod
saferequire("prototypes.entity-alternations") --Base Mod edits

logfile:write(path, "ended.\n")	-- Marking end of session
io.close(logfile)						-- Closing logfile