module(...,package.seeall)

local pos = require("posix")

local foreground = true

local function log_prefix(prio)
	local prefix = {
		[pos.LOG_INFO] = "INFO",
		[pos.LOG_ERR] = "ERROR",
		[pos.LOG_WARNING] = "WARNING",
	}
	if prefix[prio] then
		return prefix[prio]..": "
	else
		return ""
	end
end

local function log(prio, fmt, ...)
	if foreground then
		io.stderr:write(log_prefix(prio)..fmt:format(...).."\n")
	end
	pos.syslog(prio, fmt:format(...))
end

function info(fmt, ...)
	log(posix.LOG_INFO, fmt, ...)
end

function warn(fmt, ...)
	log(posix.LOG_WARNING, fmt, ...)
end

function err(fmt, ...)
	log(posix.LOG_ERR, fmt, ...)
end

function debug(fmt, ...)
	log(posix.LOG_DEBUG, fmt, ...)
end

function open(id, fg)
	foreground = fg
	pos.openlog(id)
end

function close()
	pos.closelog()
end

