-- -- lua-logfile.lua -- Lua Logfile Abstraction (language: Lua) -- Copyright (c) 2007 Ralf S. Engelschall -- -- You can redistribute and/or modify this file under the terms of -- the GNU General Public License as published by the Free Software -- Foundation; either version 2 of the License, or (at your option) any -- later version. -- -- This file is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, -- USA, or contact Ralf S. Engelschall . -- -- create namespace Logfile = {} -- object constructor Logfile.new = function (class, logfile, tag) -- create new object local self = {} setmetatable(self, class) class.__index = class -- initialize object self.fd = nil self.tag = nil self.log_level = "info" self.log_levels = { ["error"] = 1, ["warning"] = 2, ["info"] = 3, ["debug"] = 4 } -- handle convenience argument to constructor if logfile ~= nil then self:open(logfile, tag) end -- return new object return self end -- object method: logfile opening Logfile.open = function (self, logfile, tag) self.fd = io.open(logfile, "a") if self.fd == nil then io.stderr:write("ERROR: logfile:open: failed to open file \"" .. logfile .. "\"\n") return false end self.tag = tag return true end -- object method: logfile level configuration Logfile.level = function (self, level) if self.log_levels[level] == nil then io.stderr:write("ERROR: logfile:level: invalid logging level \"" .. level .. "\"\n") return end self.log_level = level return end -- object method: logfile writing Logfile.entry = function (self, level, msg) if self.log_levels[level] == nil then io.stderr:write("ERROR: logfile:entry: invalid logging level \"" .. level .. "\"\n") return end if self.log_levels[level] <= self.log_levels[self.log_level] then if level == "error" then if self.tag then io.stderr:write(tag .. ":ERROR: " .. msg .. "\n") else io.stderr:write("ERROR: " .. msg .. "\n") end end if self.fd ~= nil then local date = os.date("%Y-%m-%dT%H:%M:%S ") local txt = date if self.tag then txt = txt .. self.tag .. ": " end txt = txt .. level .. ": " txt = txt .. msg .. "\n" self.fd:write(txt) self.fd:flush() end end return end -- object method: logfile closing Logfile.close = function (self) if self.fd ~= nil then self.fd:close() self.fd = nil end return end