Jump to content


Photo

Redirecting stdout and stderr to log file


  • Please log in to reply
2 replies to this topic

#1 bryan11

bryan11
  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 18 October 2006 - 09:06 PM

For several scripts run by cron on a linux/mysql system, I'd like to log all stdout and stderr output to a file. I'm currently using this code to manually write to a log file:

$scriptName = "checkStores"; # For checkStores.php
$logPath = "/usr/local/company/bin/logs/";
$logPathAndFile = $logPath . $scriptName . ".log";
$logStart = "\n\n----" . date("Y-m-d H:i:s") . "----\nLog entry for " . $scriptName . ".php\n";
if (!$log = fopen($logPathAndFile,"a")) { echo "Cannot open log file [$logFile]\n"; }
if (!fwrite($log, $logStart)) { echo "Cannot write to log file [$logFile]\n"; }

This works, but all log entries are manual and stderr output goes to the system log. Is there a way to redirect all stdout and stderr to a log file?

Here's perl code I've recently used to log everything (stdout and stderr) to a file. An equivalent function in php is what I'm trying to build.

sub createLog
{
my $logFile = shift;
open ( STDERR, ">>$logFile" );
open ( STDOUT, ">>$logFile" );
open LOG, ">>$logFile" || die "$0: Can't open log file!";
select( LOG );
$| = 1; # Turn on buffer autoflush for log output
print "$0: Starting script ...\n";
select( STDOUT );
}

I know that one can redirect I/O from the shell, but I'd prefer to so do this within each php script.

#2 bryan11

bryan11
  • New Members
  • Pip
  • Newbie
  • 4 posts

Posted 20 October 2006 - 01:26 PM

Anyone?  You can't redirect stderr and stdout to a file in PHP?

I see some extensive error handling code in the PHP manual but can't find much on redirecting output within PHP.

#3 Daniel0

Daniel0
  • Staff Alumni
  • Advanced Member
  • 11,956 posts

Posted 20 October 2006 - 02:18 PM

Make your own function like this:
<?php
function my_fprintf($format,$stream=STDOUT)
{
	$args = func_get_args();
	if(count($args) > 2)
	{
		unset($args[0]); unset($args[1]);
		$args = array_map('addslashes',$args);
		
		$eval = "\$string = sprintf(\$format,'".join("','",$args)."');";
		
		eval($eval);
	}
	else {
		$string = sprintf($format,$stream);
	}
	$fp = @fopen('file.txt','w');
	@fwrite($string."\n");
	@fclose($fp);
	
	fprintf($string,$stream);
}

my_fprintf("%s %s",STDOUT,"test","te'st2");
?>

Not tested.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users