-- Table for System Logging
\set HOSTNAME `echo "'$HOSTNAME'"`

drop   function syslog(SysLog.systype%TYPE, SysLog.syshost%TYPE, SysLog.mod%TYPE, SysLog.func%TYPE, SysLog.msg%TYPE);
drop   table SysLog;

create table SysLog (
	syCreated	timestamp with time zone DEFAULT now(),
	systype		char(1)     DEFAULT 'E',
	syshost		text	NOT NULL,
	mod		text	NOT NULL,
	func		text	NOT NULL,
	msg		text	NOT NULL
);

comment on table SysLog is 'System log table for status about ToughLog.';
comment on column SysLog.systype is 'Type of system log.

M EMERG   0 System is unusable
A ALERT   1 Action must be taken immediately
C CRIT    2 Critical conditions
E ERR     3 Error conditions
W WARNING 4 Warning conditions
N NOTICE  5 Normal but significant condition
I INFO    6 Informational
D DEBUG   7 Debug-level messages
';
comment on column SysLog.syshost is 'Hostname of module, program or script. Typically ''$HOSTNAME''.';
comment on column SysLog.mod is 'Name of the module, program or script which add the message.';
comment on column SysLog.func is 'Internal function or other identifier inside the module.';
comment on column SysLog.msg is 'Message describing the task/problem.';

-- Usage:
-- insert into SysLog (type, mod, func, msg)
--     values ('E', 'master', 'example', 'Error message');

-- Example:
--  syslog('I', 'INSTALL', 'SysLog', 'Create table');

create or replace function syslog(SysLog.systype%TYPE, SysLog.syshost%TYPE, SysLog.mod%TYPE, SysLog.func%TYPE, SysLog.msg%TYPE) returns bool as '
declare
	p_systype alias for $1;
	p_syshost alias for $2;
	p_mod  alias for $3;
	p_func alias for $4;
	p_msg  alias for $5;
begin
	insert into SysLog(systype, syshost, mod, func, msg)
	    values(upper(p_systype), trim(p_syshost), trim(p_mod), trim(p_func), trim(p_msg));
	return true;
end;
' language 'PLpgSQL';

-- Insert first message in our new shiny table
--\set V '\'' :VERSION '\''
--select syslog('I', ':HOSTNAME', 'syslog.sql', 'VERSION', :V );
select syslog('I', :HOSTNAME, 'syslog.sql', 'INSTALL', 'Syslog table and access functions');
select syslog('I', :HOSTNAME, 'syslog.sql', 'ID', '$Id$');
select * from syslog;

-- EOF
