:- ensure_loaded(common).
cvs_id('$Id: message_hook.pl,v 1.3 2004/09/30 14:27:07 sandro Exp $').
/*

  This seems to be the standard/normal way to capture various program
  output and send it to log files, etc.  It's pretty deep in the system;
  internal prolog errors get redirected this way, too.   So be careful.

  If message_hook ends up calling print_message (perhaps because
  something it calls calls something which has some kind of prolog
  type-checking error), we end up in an infinite loop!   That case
  should at least be caught now.

*/
  
  
:- multifile message_hook/3.
:- dynamic message_hook/3.         % why?!?!

:- ensure_loaded(time_conversions).
:- ensure_loaded(stack).
:- ensure_loaded(mkdir).

:- thread_local(in_message_hook).

%%
%%  dynamic: redirect_messages_to_queue(?Term, ?QueuePredicate)
%%
%%  QueuePredicate is assertz'd, after adding Term, Kind, Lines
%%
:- multifile redirect_messages_to_queue/3.
:- dynamic redirect_messages_to_queue/3.

message_hook(Term, Kind, Lines) :-

	thread_self(Thread),
	redirect_messages_to_queue(Thread, Term, Queue),
	Queue =.. F,
	append(F, [Term, Kind, Lines], F2),
	Q2 =.. F2,
	assertz(Q2).

/*

	call(Hook, Term, Kind, Lines).
	% temporary hook....   testing SGML
	functor(Term, Functor),
	(   member(Functor, [rdf, sgml]),
	->  % trap the error here
	    
	
	format(user_error, '[hook] ~q ~q ~q~n', [Term, Kind, Lines]).


  
	
	% fail (dont take the hook) unless this is set....
	flag(output_to_logs, SL, SL),
	SL = true,

	% okay, we're taking the hook....

	(   in_message_hook
	->  format(user_error, '~n~n*** Recursive call to message_hook', []),
	    halt
	;   assert(in_message_hook)
	),

	'$messages':print_system_message(Term, Kind, Lines),
	
	get_time(Now),
	isotime(Now, NowIso),
	concat_atom([NowIso, ' (', Kind ,') '], Prefix),

	% ADD A STACK TRACE
	(   (Kind = error ; Kind = warning)
	->  stack_trace(Trace2),
	    Trace=['~n=== Stack Trace===~n'|Trace2],
	    append(Lines, Trace, LinesPlus)
	;   Lines = LinesPlus
	),

	(   (Kind = error ; Kind = warning)
	->  log_message(errors, Prefix, Lines)
	;   true
	),
	
	log_message(messages, Prefix,  LinesPlus),

	%'$messages':print_system_message(Term, Kind, LinesPlus).
	/*
	% REPORT IT NORMALLY (MAYBE)
	flag(no_output, SL, SL),
	(   fail
	->  true
	;   '$messages':print_system_message(Term, Kind, LinesPlus)
	).
	  */

	retract(in_message_hook).

*/
